|
| 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