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 ( b5171f...3084d7 )
by Cees-Jan
03:40 queued 01:35
created

WebrootPreloadMiddleware::__construct()   B

Complexity

Conditions 7
Paths 20

Size

Total Lines 57
Code Lines 37

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 37
CRAP Score 7

Importance

Changes 0
Metric Value
cc 7
eloc 37
nc 20
nop 3
dl 0
loc 57
ccs 37
cts 37
cp 1
crap 7
rs 8.3946
c 0
b 0
f 0

How to fix   Long Method   

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 Narrowspark\Mimetypes\MimeTypeByExtensionGuesser;
6
use Psr\Http\Message\ServerRequestInterface;
7
use Psr\Log\LoggerInterface;
8
use React\Cache\ArrayCache;
9
use React\Cache\CacheInterface;
10
use RingCentral\Psr7\Response;
11
use ScriptFUSION\Byte\ByteFormatter;
12
use function RingCentral\Psr7\stream_for;
13
14
final class WebrootPreloadMiddleware
15
{
16
    /** @var CacheInterface */
17
    private $cache;
18
19 13
    public function __construct(string $webroot, LoggerInterface $logger = null, CacheInterface $cache = null)
20
    {
21 13
        $this->cache = $cache ?? new ArrayCache();
22
23 13
        $totalSize = 0;
24 13
        $count = 0;
25 13
        $byteFormatter = (new ByteFormatter())->setPrecision(2)->setFormat('%v%u');
26 13
        $directory = new \RecursiveDirectoryIterator($webroot);
27 13
        $directory = new \RecursiveIteratorIterator($directory);
28 13
        $directory = iterator_to_array($directory);
29
        usort($directory, function ($a, $b) {
30 13
            return $a->getPathname() <=> $b->getPathname();
31 13
        });
32 13
        foreach ($directory as $fileinfo) {
33 13
            if (!$fileinfo->isFile()) {
34 13
                continue;
35
            }
36
37 13
            $filePath = str_replace(
38
                [
39 13
                    $webroot,
40 13
                    DIRECTORY_SEPARATOR,
41 13
                    '//',
42
                ],
43
                [
44 13
                    DIRECTORY_SEPARATOR,
45 13
                    '/',
46 13
                    '/',
47
                ],
48 13
                $fileinfo->getPathname()
49
            );
50
51
            $item = [
52 13
                'contents' => file_get_contents($fileinfo->getPathname()),
53
            ];
54 13
            $item['etag'] = md5($item['contents']) . '-' . filesize($fileinfo->getPathname());
55
56 13
            $mime = MimeTypeByExtensionGuesser::guess($fileinfo->getExtension());
57 13
            if (is_null($mime)) {
58 13
                $mime = 'application/octet-stream';
59
            }
60 13
            list($mime) = explode(';', $mime);
61 13
            if (strpos($mime, '/') !== false) {
62 13
                $item['mime'] = $mime;
63
            }
64
65 13
            $this->cache->set($filePath, $item);
66 13
            $count++;
67 13
            if ($logger instanceof LoggerInterface) {
68 1
                $fileSize = strlen($item['contents']);
69 1
                $totalSize += $fileSize;
70 13
                $logger->debug($filePath . ': ' . $byteFormatter->format($fileSize) . ' (' . $item['mime'] . ')');
71
            }
72
        }
73
74 13
        if ($logger instanceof LoggerInterface) {
75 1
            $logger->info('Preloaded ' . $count . ' file(s) with a combined size of ' . $byteFormatter->format($totalSize) . ' from "' . $webroot . '" into memory');
76
        }
77 13
    }
78
79 12
    public function __invoke(ServerRequestInterface $request, callable $next)
80
    {
81 12
        $path = $request->getUri()->getPath();
82
83
        return $this->cache->get($path)->then(function ($item) use ($next, $request) {
84 12
            if ($item === null) {
85 1
                return $next($request);
86
            }
87
88 11
            if ($request->hasHeader('If-None-Match')) {
89 3
                $etag = current($request->getHeader('If-None-Match'));
90 3
                $etag = trim($etag, '"');
91 3
                if ($etag === $item['etag']) {
92
                    return new Response(304);
93
                }
94
            }
95
96 11
            $response = (new Response(200))->
97 11
                withBody(stream_for($item['contents']))->
98 11
                withHeader('ETag', '"' . $item['etag'] . '"')
99
            ;
100 11
            if (!isset($item['mime'])) {
101
                return $response;
102
            }
103
104 11
            return $response->withHeader('Content-Type', $item['mime']);
105 12
        });
106
    }
107
}
108