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.
Passed
Pull Request — master (#2)
by Cees-Jan
07:25 queued 05:23
created

ResponseCacheMiddleware::__invoke()   C

Complexity

Conditions 12
Paths 5

Size

Total Lines 52
Code Lines 33

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 30
CRAP Score 12.0351

Importance

Changes 0
Metric Value
dl 0
loc 52
ccs 30
cts 32
cp 0.9375
rs 5.9842
c 0
b 0
f 0
cc 12
eloc 33
nc 5
nop 2
crap 12.0351

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php declare(strict_types=1);
2
3
namespace WyriHaximus\React\Http\Middleware;
4
5
use Psr\Http\Message\ResponseInterface;
6
use Psr\Http\Message\ServerRequestInterface;
7
use React\Cache\ArrayCache;
8
use React\Cache\CacheInterface;
9
use React\Http\Io\HttpBodyStream;
10
use React\Http\Response;
11
use function React\Promise\resolve;
12
use function RingCentral\Psr7\stream_for;
13
14
final class ResponseCacheMiddleware
15
{
16
    const PREFIX_WITHOUT_QUERY = '***';
17
    const PREFIX_WITH_QUERY = '???';
18
    const PREFIXES = [
19
        self::PREFIX_WITH_QUERY,
20
        self::PREFIX_WITHOUT_QUERY,
21
    ];
22
23
    /**
24
     * @var array
25
     */
26
    private $staticUrls = [];
27
28
    /**
29
     * @var array
30
     */
31
    private $prefixUrlsWithoutQuery = [];
32
33
    /**
34
     * @var array
35
     */
36
    private $prefixUrlsWithQuery = [];
37
38
    /**
39
     * @var CacheInterface
40
     */
41
    private $cache;
42
43
    /**
44
     * @param array               $urls
45
     * @param array               $headers
46
     * @param CacheInterface|null $cache
47 1
     */
48
    public function __construct(array $urls, array $headers = [], CacheInterface $cache = null)
49 1
    {
50 1
        $this->sortUrls($urls);
51 1
        $this->headers = $headers;
0 ignored issues
show
Bug Best Practice introduced by
The property headers does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
52 1
        $this->cache = $cache instanceof CacheInterface ? $cache : new ArrayCache();
53
    }
54 1
55
    public function __invoke(ServerRequestInterface $request, callable $next)
56 1
    {
57
        if ($request->getMethod() !== 'GET') {
58
            return resolve($next($request));
59
        }
60
61 1
        if (
62 1
            class_exists(SessionMiddleware::class) &&
63 1
            $request->getAttribute(SessionMiddleware::ATTRIBUTE_NAME) !== null &&
64
            $request->getAttribute(SessionMiddleware::ATTRIBUTE_NAME)->isActive() === true
65 1
        ) {
66
            return resolve($next($request));
67
        }
68 1
69 1
        $uri = $request->getUri()->getPath();
70 1
        if (!in_array($uri, $this->staticUrls, true) && !$this->matchesPrefixUrl($uri)) {
71
            return resolve($next($request));
72
        }
73 1
74 1
        $key = $uri;
75 1
        $query = $request->getUri()->getQuery();
76 1
        if (strlen($query) > 0 && $this->queryInKey($uri)) {
77
            $key .= '?' . $query;
78
        }
79 1
80 1
        return $this->cache->get($key)->then(function ($json) {
81
            $cachedResponse = json_decode($json);
82 1
83
            return new Response($cachedResponse->code, (array)$cachedResponse->headers, stream_for($cachedResponse->body));
84 1
        }, function () use ($next, $request, $key) {
85 1
            return resolve($next($request))->then(function (ResponseInterface $response) use ($key) {
86 1
                if ($response->getBody() instanceof HttpBodyStream) {
87
                    return $response;
88
                }
89 1
90 1
                $body = (string)$response->getBody();
91 1
                $headers = [];
92 1
                foreach ($this->headers as $header) {
93
                    if (!$response->hasHeader($header)) {
94
                        continue;
95
                    }
96 1
97
                    $headers[$header] = $response->getHeaderLine($header);
98 1
                }
99 1
                $cachedResponse = json_encode([
100 1
                    'body' => $body,
101 1
                    'headers' => $headers,
102
                    'code' => $response->getStatusCode(),
103 1
                ]);
104
                $this->cache->set($key, $cachedResponse);
105 1
106 1
                return $response->withBody(stream_for($body));
107 1
            });
108
        });
109
    }
110 1
111
    private function sortUrls(array $urls)
112 1
    {
113 1
        foreach ($urls as $url) {
114 1
            if (!(strlen($url) >= 3 && in_array(substr($url, -3), self::PREFIXES, true))) {
115
                $this->staticUrls[] = $url;
116 1
117
                continue;
118
            }
119 1
120 1
            if (strlen($url) >= 3 && substr($url, -3) === self::PREFIX_WITHOUT_QUERY) {
121
                $this->prefixUrlsWithoutQuery[] = substr($url, 0, -3);
122 1
123
                continue;
124
            }
125 1
126 1
            if (strlen($url) >= 3 && substr($url, -3) === self::PREFIX_WITH_QUERY) {
127
                $this->prefixUrlsWithQuery[] = substr($url, 0, -3);
128 1
129
                continue;
130
            }
131 1
        }
132
    }
133 1
134
    private function matchesPrefixUrl(string $uri): bool
135 1
    {
136 1
        if ($this->urlMatchesPrefixes($this->prefixUrlsWithoutQuery, $uri)) {
137
            return true;
138
        }
139 1
140
        return $this->urlMatchesPrefixes($this->prefixUrlsWithQuery, $uri);
141
    }
142 1
143
    private function queryInKey(string $uri): bool
144 1
    {
145
        return $this->urlMatchesPrefixes($this->prefixUrlsWithQuery, $uri);
146
    }
147 1
148
    private function urlMatchesPrefixes(array $urls, string $uri): bool
149 1
    {
150 1
        foreach ($urls as $url) {
151 1
            $urlLength = strlen($url);
152 1
            if (substr($uri, 0, $urlLength) === $url) {
153
                return true;
154
            }
155
        }
156 1
157
        return false;
158
    }
159
}
160