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 (#16)
by Cees-Jan
05:44 queued 03:30
created

WebrootPreloadMiddleware   A

Complexity

Total Complexity 15

Size/Duplication

Total Lines 100
Duplicated Lines 0 %

Test Coverage

Coverage 91.38%

Importance

Changes 0
Metric Value
eloc 58
dl 0
loc 100
ccs 53
cts 58
cp 0.9138
rs 10
c 0
b 0
f 0
wmc 15

2 Methods

Rating   Name   Duplication   Size   Complexity  
B __construct() 0 57 7
B __invoke() 0 35 8
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 2
                    return new Response(304);
93
                }
94
            }
95
96 9
            if ($request->hasHeader('If-Match')) {
97
                foreach ($request->gethHeader('If-Match') as $expectedEtag) {
0 ignored issues
show
Bug introduced by
The method gethHeader() does not exist on Psr\Http\Message\ServerRequestInterface. Did you maybe mean getHeader()? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

97
                foreach ($request->/** @scrutinizer ignore-call */ gethHeader('If-Match') as $expectedEtag) {

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
98
                    $expectedEtag = trim($expectedEtag, '"');
99
                    if ($expectedEtag !== $item['etag']) {
100
                        return new Response(412);
101
                    }
102
                }
103
            }
104
105 9
            $response = (new Response(200))->
106 9
                withBody(stream_for($item['contents']))->
107 9
                withHeader('ETag', '"' . $item['etag'] . '"')
108
            ;
109 9
            if (!isset($item['mime'])) {
110
                return $response;
111
            }
112
113 9
            return $response->withHeader('Content-Type', $item['mime']);
114 12
        });
115
    }
116
}
117