Skip to content

Commit c28f84e

Browse files
authored
Merge pull request #73 from blitz-php/devs
feat: ajout du middleware `FileViewer`
2 parents 49f2f41 + 9dd9d31 commit c28f84e

1 file changed

Lines changed: 74 additions & 0 deletions

File tree

src/Middlewares/FileViewer.php

Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
<?php
2+
3+
/**
4+
* This file is part of Blitz PHP framework.
5+
*
6+
* (c) 2022 Dimitri Sitchet Tomkeu <devcode.dst@gmail.com>
7+
*
8+
* For the full copyright and license information, please view
9+
* the LICENSE file that was distributed with this source code.
10+
*/
11+
12+
namespace BlitzPHP\Middlewares;
13+
14+
use BlitzPHP\Filesystem\Adapters\FilesystemAdapter;
15+
use BlitzPHP\Filesystem\Exceptions\FileNotFoundException;
16+
use BlitzPHP\Filesystem\FilesystemManager;
17+
use BlitzPHP\Http\Request;
18+
use BlitzPHP\Http\Response;
19+
use Psr\Http\Message\ResponseInterface;
20+
use Psr\Http\Message\ServerRequestInterface;
21+
use Psr\Http\Server\MiddlewareInterface;
22+
use Psr\Http\Server\RequestHandlerInterface;
23+
24+
class FileViewer implements MiddlewareInterface
25+
{
26+
/**
27+
* Chemin d'accès du fichier qu'on souhaite affiché
28+
*/
29+
private string $path = '';
30+
31+
private ?FilesystemAdapter $disk = null;
32+
33+
public function __construct(private FilesystemManager $filesystem, private Response $response)
34+
{
35+
}
36+
37+
/**
38+
* @param Request $request
39+
*/
40+
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
41+
{
42+
$config = config('filesystems');
43+
44+
if ([] === ($config['viewable'] ?? [])) {
45+
return $handler->handle($request);
46+
}
47+
48+
$path = trim(urldecode($request->getPath()), '/');
49+
[$prefix, $this->path] = explode('/', $path, 2);
50+
51+
foreach ($config['disks'] as $name => $disk) {
52+
if (str_ends_with(trim($disk['url'], '/'), trim($prefix, '/'))) {
53+
$this->disk = $this->filesystem->disk($name); // @phpstan-ignore-line
54+
break;
55+
}
56+
}
57+
58+
if (null === $this->disk) {
59+
return $handler->handle($request);
60+
}
61+
62+
if (! $this->disk->exists($this->path)) {
63+
throw FileNotFoundException::fileNotFound($this->path);
64+
}
65+
66+
$path = $this->disk->path($this->path);
67+
68+
if ($request->boolean('download')) {
69+
return $this->response->download($path);
70+
}
71+
72+
return $this->response->file($path);
73+
}
74+
}

0 commit comments

Comments
 (0)