Ecodev /
felix
| 1 | <?php |
||
| 2 | |||
| 3 | declare(strict_types=1); |
||
| 4 | |||
| 5 | namespace Ecodev\Felix\Handler; |
||
| 6 | |||
| 7 | use Doctrine\Persistence\ObjectRepository; |
||
| 8 | use Ecodev\Felix\Model\File; |
||
| 9 | use Laminas\Diactoros\Response; |
||
| 10 | use Psr\Http\Message\ResponseInterface; |
||
| 11 | use Psr\Http\Message\ServerRequestInterface; |
||
| 12 | |||
| 13 | final class FileHandler extends AbstractHandler |
||
| 14 | { |
||
| 15 | public function __construct(private readonly ObjectRepository $fileRepository) |
||
|
0 ignored issues
–
show
Bug
introduced
by
Loading history...
|
|||
| 16 | { |
||
| 17 | } |
||
| 18 | |||
| 19 | /** |
||
| 20 | * Serve a downloaded file from disk. |
||
| 21 | */ |
||
| 22 | public function handle(ServerRequestInterface $request): ResponseInterface |
||
| 23 | { |
||
| 24 | $id = (int) $request->getAttribute('id'); |
||
| 25 | |||
| 26 | /** @var null|File $file */ |
||
| 27 | $file = $this->fileRepository->find($id); |
||
| 28 | if (!$file) { |
||
| 29 | return $this->createError("File $id not found in database"); |
||
| 30 | } |
||
| 31 | |||
| 32 | $path = $file->getPath(); |
||
| 33 | if (!is_readable($path)) { |
||
| 34 | return $this->createError("File for $id not found on disk, or not readable"); |
||
| 35 | } |
||
| 36 | |||
| 37 | $resource = fopen($path, 'rb'); |
||
| 38 | if ($resource === false) { |
||
| 39 | return $this->createError("Cannot open file for $id on disk"); |
||
| 40 | } |
||
| 41 | $size = filesize($path); |
||
| 42 | $type = mime_content_type($path); |
||
| 43 | $response = new Response($resource, 200, ['content-type' => $type, 'content-length' => $size]); |
||
| 44 | |||
| 45 | return $response; |
||
| 46 | } |
||
| 47 | } |
||
| 48 |