-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathExampleMiddleware.php
More file actions
102 lines (86 loc) · 3.09 KB
/
Copy pathExampleMiddleware.php
File metadata and controls
102 lines (86 loc) · 3.09 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
<?php
declare(strict_types=1);
namespace SpazzMarticus\Example;
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;
use RecursiveDirectoryIterator;
use RecursiveIteratorIterator;
use RuntimeException;
final readonly class ExampleMiddleware implements MiddlewareInterface
{
public function __construct(
private ResponseFactoryInterface $responseFactory,
private StreamFactoryInterface $streamFactory,
private string $uploadDirectory,
private string $chunkDirectory,
private string $storageDirectory,
) {}
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
{
if ($request->getMethod() === 'GET') {
if ($request->getUri()->getPath() === '/reset') {
/**
* Reset upload directory and cache
*/
$this->deleteDirectories($this->uploadDirectory);
$this->deleteDirectories($this->chunkDirectory);
$this->deleteDirectories($this->storageDirectory);
return $this->responseFactory->createResponse(302)
->withHeader('Location', '/') //Redirect back to root
;
}
if ($request->getUri()->getPath() === '/' && $request->getQueryParams() === []) {
/**
* Serve uploader
*/
return $this->responseFactory->createResponse()
->withBody($this->streamFactory->createStreamFromFile(__DIR__ . '/uploader.html'))
;
}
}
$this->createDir($this->uploadDirectory);
$this->createDir($this->chunkDirectory);
$this->createDir($this->storageDirectory);
/**
* Pass request to tus server
*/
return $handler->handle($request);
}
/**
* https://stackoverflow.com/a/3349792 - Delete directory with files in it?
* @param string $dir Directory to delete
*/
private function deleteDirectories(string $dir): void
{
if (is_dir($dir)) {
$it = new RecursiveDirectoryIterator($dir, \FilesystemIterator::SKIP_DOTS);
$files = new RecursiveIteratorIterator(
$it,
RecursiveIteratorIterator::CHILD_FIRST
);
foreach ($files as $file) {
\assert($file instanceof \SplFileObject);
if ($file->isDir()) {
rmdir($file->getRealPath());
} else {
unlink($file->getRealPath());
}
}
rmdir($dir);
}
}
private function createDir(string $dir): void
{
if (is_dir($dir)) {
return;
}
if (@mkdir($dir, 0o777, true)) {
return;
}
throw new RuntimeException("Can't create directory");
}
}