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
Pull Request — master (#5)
by Cees-Jan
04:02
created

SessionMiddleware::fetchSessionDataFromCache()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 16

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 3.0987

Importance

Changes 0
Metric Value
dl 0
loc 16
ccs 7
cts 9
cp 0.7778
rs 9.7333
c 0
b 0
f 0
cc 3
nc 2
nop 1
crap 3.0987
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
     * @param SessionIdInterface|null $sessionId
52
     */
53 12
    public function __construct(
54
        string $cookieName,
55
        CacheInterface $cache,
56
        array $cookieParams = [],
57
        SessionIdInterface $sessionId = null
58
    ) {
59 12
        $this->cookieName = $cookieName;
60 12
        $this->cache = $cache;
61 12
        $this->cookieParams = array_replace(self::DEFAULT_COOKIE_PARAMS, $cookieParams);
62
63 12
        if ($sessionId === null) {
64 12
            $sessionId = new RandomBytes();
65
        }
66 12
        $this->sessionId = $sessionId;
67 12
    }
68
69
    public function __invoke(ServerRequestInterface $request, callable $next)
70
    {
71 12
        return $this->fetchSessionFromRequest($request)->then(function (Session $session) use ($next, $request) {
72 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...
73
74 12
            return resolve(
75 12
                $next($request)
76
            )->then(function (ResponseInterface $response) use ($session) {
77 12
                return $this->updateCache($session)->then(function () use ($response) {
78 12
                    return $response;
79 12
                });
80
            })->then(function ($response) use ($session) {
81 12
                $cookie = $this->getCookie($session);
82 12
                $response = $cookie->addToResponse($response);
83
84 12
                return $response;
85 12
            });
86 12
        });
87
    }
88
89 12
    private function fetchSessionFromRequest(ServerRequestInterface $request): PromiseInterface
90
    {
91 12
        $id = '';
92 12
        $cookies = RequestCookies::createFromRequest($request);
93
94
        try {
95 12
            if (!$cookies->has($this->cookieName)) {
96 10
                return resolve(new Session($id, [], $this->sessionId));
97
            }
98 2
            $id = $cookies->get($this->cookieName)->getValue();
99
100 2
            return $this->fetchSessionDataFromCache($id)->then(function (array $sessionData) use ($id) {
101 2
                return new Session($id, $sessionData, $this->sessionId);
102 2
            });
103
        } catch (Throwable $et) {
104
            // Do nothing, only a not found will be thrown so generating our own id now
105
        }
106
107
        return resolve(new Session($id, [], $this->sessionId));
108
    }
109
110 2
    private function fetchSessionDataFromCache(string $id): PromiseInterface
111
    {
112 2
        if ($id === '') {
113
            return resolve([]);
114
        }
115
116 2
        return $this->cache->get($id)->then(function ($result) {
117 2
            if ($result === null) {
118 1
                return resolve([]);
119
            }
120
121 1
            return $result;
122
        }, function () {
123
            return resolve([]);
124 2
        });
125
    }
126
127 12
    private function updateCache(Session $session): PromiseInterface
128
    {
129 12
        foreach ($session->getOldIds() as $oldId) {
130 1
            $this->cache->delete($oldId);
131
        }
132
133 12
        if ($session->isActive()) {
134 10
            return resolve($this->cache->set($session->getId(), $session->getContents()));
135
        }
136
137 2
        return resolve();
138
    }
139
140 12
    private function getCookie(Session $session): SetCookie
141
    {
142 12
        $cookieParams = $this->cookieParams;
143
144 12
        if ($session->isActive()) {
145
            // Only set time when expires is set in the future
146 10
            if ($cookieParams[0] > 0) {
147 8
                $cookieParams[0] += time();
148
            }
149
150 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...
151
        }
152 2
        unset($cookieParams[0]);
153
154 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...
155
    }
156
}
157