-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathStaticFileMiddleware.php
More file actions
143 lines (115 loc) · 4.66 KB
/
Copy pathStaticFileMiddleware.php
File metadata and controls
143 lines (115 loc) · 4.66 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
<?php
declare(strict_types=1);
namespace Chubbyphp\StaticFile;
use Psr\Http\Message\ResponseFactoryInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Message\StreamFactoryInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;
final class StaticFileMiddleware implements MiddlewareInterface
{
private readonly string $hashAlgorithm;
/**
* @var array<string, string>
*/
private readonly array $mimetypes;
/**
* @param null|array<string, string> $mimetypes
*/
public function __construct(
private readonly ResponseFactoryInterface $responseFactory,
private readonly StreamFactoryInterface $streamFactory,
private readonly string $publicDirectory,
string $hashAlgorithm = 'md5',
?array $mimetypes = null,
) {
if (!\in_array($hashAlgorithm, hash_algos(), true)) {
throw new \LogicException(\sprintf('Invalid or not supported hash algorithm: "%s"', $hashAlgorithm));
}
$this->hashAlgorithm = $hashAlgorithm;
$this->mimetypes = $mimetypes ?? require __DIR__.'/mimetypes.php';
}
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
{
$filename = $this->resolveFilename($request);
$response = null !== $filename ? $this->createFileResponse($request, $filename) : null;
return $response ?? $handler->handle($request);
}
private function resolveFilename(ServerRequestInterface $request): ?string
{
$publicDirectory = realpath($this->publicDirectory);
if (false === $publicDirectory || !is_dir($publicDirectory)) {
return null;
}
$requestTarget = $request->getRequestTarget();
$requestPath = substr($requestTarget, 0, strcspn($requestTarget, '?'));
$filename = realpath($publicDirectory.$requestPath);
if (
false === $filename
|| !str_starts_with($filename, rtrim($publicDirectory, \DIRECTORY_SEPARATOR).\DIRECTORY_SEPARATOR)
|| !is_file($filename)
|| !is_readable($filename)
) {
return null;
}
return $filename;
}
private function createFileResponse(ServerRequestInterface $request, string $filename): ?ResponseInterface
{
$method = $request->getMethod();
if (!\in_array($method, ['GET', 'HEAD'], true)) {
return null;
}
$fileSize = @filesize($filename);
$hash = @hash_file($this->hashAlgorithm, $filename);
if (!\is_int($fileSize) || !\is_string($hash)) {
return null;
}
$etag = '"'.$hash.'"';
return $this->matchesIfNoneMatch($request->getHeaderLine('If-None-Match'), $etag)
? $this->createResponse(304, $filename, $fileSize, $etag)
: $this->createBodyResponse($method, $filename, $fileSize, $etag);
}
private function createBodyResponse(string $method, string $filename, int $fileSize, string $etag): ?ResponseInterface
{
$response = $this->createResponse(200, $filename, $fileSize, $etag);
if ('HEAD' === $method) {
return $response;
}
try {
return $response->withBody($this->streamFactory->createStreamFromFile($filename));
} catch (\RuntimeException) {
return null;
}
}
private function createResponse(int $code, string $filename, int $fileSize, string $etag): ResponseInterface
{
$response = $this->responseFactory->createResponse($code);
$response = $response->withHeader('Content-Length', (string) $fileSize);
$response = $this->addContentType($response, $filename);
$response = $response->withHeader('X-Content-Type-Options', 'nosniff');
return $response->withHeader('ETag', $etag);
}
private function matchesIfNoneMatch(string $header, string $etag): bool
{
foreach (explode(',', $header) as $candidate) {
$candidate = trim($candidate);
if ('*' === $candidate) {
return true;
}
if (str_starts_with($candidate, 'W/')) {
$candidate = substr($candidate, 2);
}
if ($etag === $candidate) {
return true;
}
}
return false;
}
private function addContentType(ResponseInterface $response, string $filename): ResponseInterface
{
$extension = pathinfo($filename, PATHINFO_EXTENSION);
return $response->withHeader('Content-Type', $this->mimetypes[$extension] ?? 'application/octet-stream');
}
}