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 ( 9fa28b...676e51 )
by Cees-Jan
10s
created

WebrootPreloadMiddleware::__invoke()   A

Complexity

Conditions 3
Paths 1

Size

Total Lines 15
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 3.0175

Importance

Changes 0
Metric Value
cc 3
eloc 8
nc 1
nop 2
dl 0
loc 15
ccs 7
cts 8
cp 0.875
crap 3.0175
rs 10
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
55 10
            $mime = MimeTypeByExtensionGuesser::guess($fileinfo->getExtension());
56 10
            if (is_null($mime)) {
57 10
                $mime = 'application/octet-stream';
58
            }
59 10
            list($mime) = explode(';', $mime);
60 10
            if (strpos($mime, '/') !== false) {
61 10
                $item['mime'] = $mime;
62
            }
63
64 10
            $this->cache->set($filePath, $item);
65 10
            $count++;
66 10
            if ($logger instanceof LoggerInterface) {
67 1
                $fileSize = strlen($item['contents']);
68 1
                $totalSize += $fileSize;
69 10
                $logger->debug($filePath . ': ' . $byteFormatter->format($fileSize) . ' (' . $item['mime'] . ')');
70
            }
71
        }
72
73 10
        if ($logger instanceof LoggerInterface) {
74 1
            $logger->info('Preloaded ' . $count . ' file(s) with a combined size of ' . $byteFormatter->format($totalSize) . ' from "' . $webroot . '" into memory');
75
        }
76 10
    }
77
78 9
    public function __invoke(ServerRequestInterface $request, callable $next)
79
    {
80 9
        $path = $request->getUri()->getPath();
81
82
        return $this->cache->get($path)->then(function ($item) use ($next, $request) {
83 9
            if ($item === null) {
84 1
                return $next($request);
85
            }
86
87 8
            $response = (new Response(200))->withBody(stream_for($item['contents']));
88 8
            if (!isset($item['mime'])) {
89
                return $response;
90
            }
91
92 8
            return $response->withHeader('Content-Type', $item['mime']);
93 9
        });
94
    }
95
}
96