| Total Complexity | 5 |
| Total Lines | 36 |
| Duplicated Lines | 0 % |
| Coverage | 0% |
| Changes | 0 | ||
| 1 | <?php |
||
| 13 | final class FileHandler extends AbstractHandler |
||
| 14 | { |
||
| 15 | public function __construct(private readonly ObjectRepository $fileRepository) |
||
|
|
|||
| 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 |