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 ( 678234...b5171f )
by Cees-Jan
02:18
created

WebrootPreloadMiddleware::__invoke()   A

Complexity

Conditions 3
Paths 1

Size

Total Lines 18
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 3.009

Importance

Changes 0
Metric Value
cc 3
eloc 10
nc 1
nop 2
dl 0
loc 18
ccs 9
cts 10
cp 0.9
crap 3.009
rs 9.9332
c 0
b 0
f 0
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 10
    public function __construct(string $webroot, LoggerInterface $logger = null, CacheInterface $cache = null)
20
    {
21 10
        $this->cache = $cache ?? new ArrayCache();
22
23 10
        $totalSize = 0;
24 10
        $count = 0;
25 10
        $byteFormatter = (new ByteFormatter())->setPrecision(2)->setFormat('%v%u');
26 10
        $directory = new \RecursiveDirectoryIterator($webroot);
27 10
        $directory = new \RecursiveIteratorIterator($directory);
28 10
        $directory = iterator_to_array($directory);
29
        usort($directory, function ($a, $b) {
30 10
            return $a->getPathname() <=> $b->getPathname();
31 10
        });
32 10
        foreach ($directory as $fileinfo) {
33 10
            if (!$fileinfo->isFile()) {
34 10
                continue;
35
            }
36
37 10
            $filePath = str_replace(
38
                [
39 10
                    $webroot,
40 10
                    DIRECTORY_SEPARATOR,
41 10
                    '//',
42
                ],
43
                [
44 10
                    DIRECTORY_SEPARATOR,
45 10
                    '/',
46 10
                    '/',
47
                ],
48 10
                $fileinfo->getPathname()
49
            );
50
51
            $item = [
52 10
                'contents' => file_get_contents($fileinfo->getPathname()),
53
            ];
54 10
            $item['etag'] = md5($item['contents']) . '-' . filesize($fileinfo->getPathname());
55
56 10
            $mime = MimeTypeByExtensionGuesser::guess($fileinfo->getExtension());
57 10
            if (is_null($mime)) {
58 10
                $mime = 'application/octet-stream';
59
            }
60 10
            list($mime) = explode(';', $mime);
61 10
            if (strpos($mime, '/') !== false) {
62 10
                $item['mime'] = $mime;
63
            }
64
65 10
            $this->cache->set($filePath, $item);
66 10
            $count++;
67 10
            if ($logger instanceof LoggerInterface) {
68 1
                $fileSize = strlen($item['contents']);
69 1
                $totalSize += $fileSize;
70 10
                $logger->debug($filePath . ': ' . $byteFormatter->format($fileSize) . ' (' . $item['mime'] . ')');
71
            }
72
        }
73
74 10
        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 10
    }
78
79 9
    public function __invoke(ServerRequestInterface $request, callable $next)
80
    {
81 9
        $path = $request->getUri()->getPath();
82
83
        return $this->cache->get($path)->then(function ($item) use ($next, $request) {
84 9
            if ($item === null) {
85 1
                return $next($request);
86
            }
87
88 8
            $response = (new Response(200))->
89 8
                withBody(stream_for($item['contents']))->
90 8
                withHeader('ETag', $item['etag'])
91
            ;
92 8
            if (!isset($item['mime'])) {
93
                return $response;
94
            }
95
96 8
            return $response->withHeader('Content-Type', $item['mime']);
97 9
        });
98
    }
99
}
100