DownloadRequestDataProvider.php 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. <?php
  2. declare(strict_types=1);
  3. namespace App\DataProvider\Core;
  4. use ApiPlatform\Core\DataProvider\ItemDataProviderInterface;
  5. use ApiPlatform\Core\DataProvider\RestrictedDataProviderInterface;
  6. use App\ApiResources\DownloadRequest;
  7. use App\Enum\Core\FileStatusEnum;
  8. use App\Repository\Core\FileRepository;
  9. use App\Service\File\FileManager;
  10. use Symfony\Component\HttpFoundation\HeaderUtils;
  11. use Symfony\Component\HttpFoundation\RedirectResponse;
  12. use Symfony\Component\HttpFoundation\Response;
  13. use Symfony\Bundle\SecurityBundle\Security;
  14. /**
  15. * Custom provider pour le téléchargement des fichiers du LocalStorage
  16. */
  17. final class DownloadRequestDataProvider implements ItemDataProviderInterface, RestrictedDataProviderInterface
  18. {
  19. public function __construct(
  20. private FileRepository $fileRepository,
  21. private FileManager $fileManager,
  22. private Security $security,
  23. )
  24. {}
  25. public function supports(string $resourceClass, string $operationName = null, array $context = []): bool
  26. {
  27. return DownloadRequest::class === $resourceClass;
  28. }
  29. public function getItem(string $resourceClass, $id, string $operationName = null, array $context = []): Response | RedirectResponse
  30. {
  31. $file = $this->fileRepository->find($id);
  32. if (empty($file)) {
  33. throw new \RuntimeException("File " . $id . " does not exist; abort.");
  34. }
  35. if ($file->getStatus() !== FileStatusEnum::READY()->getValue()) {
  36. throw new \RuntimeException("File " . $id . " has " . $file->getStatus() . " status; abort.");
  37. }
  38. // Read the file
  39. $token = $this->security->getToken();
  40. $content = $this->fileManager->read($file, $token);
  41. // Build the response and attach the file to it
  42. // @see https://symfony.com/doc/current/components/http_foundation.html#serving-files
  43. $response = new Response($content);
  44. $response->headers->set('Charset', 'UTF-8');
  45. $response->headers->set('Access-Control-Expose-Headers', 'Content-Disposition');
  46. if (!empty($file->getMimeType())) {
  47. $response->headers->set('Content-Type', $file->getMimeType());
  48. }
  49. $response->headers->set(
  50. 'Content-Disposition',
  51. HeaderUtils::makeDisposition(HeaderUtils::DISPOSITION_ATTACHMENT, $file->getName())
  52. );
  53. return $response;
  54. }
  55. }