| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687 |
- <?php
- declare(strict_types=1);
- namespace App\State\Provider\Core;
- use ApiPlatform\Metadata\GetCollection;
- use ApiPlatform\Metadata\Operation;
- use ApiPlatform\State\ProviderInterface;
- use App\ApiResources\DownloadRequest;
- use App\Enum\Core\FileStatusEnum;
- use App\Repository\Core\FileRepository;
- use App\Service\File\Exception\FileNotFoundException;
- use App\Service\File\FileManager;
- use RuntimeException;
- use Symfony\Component\HttpFoundation\HeaderUtils;
- use Symfony\Component\HttpFoundation\RedirectResponse;
- use Symfony\Component\HttpFoundation\Response;
- use Symfony\Bundle\SecurityBundle\Security;
- /**
- * Custom provider pour le téléchargement des fichiers du LocalStorage
- */
- final class DownloadRequestProvider implements ProviderInterface
- {
- public function __construct(
- private FileRepository $fileRepository,
- private FileManager $fileManager,
- private Security $security,
- )
- {}
- /**
- * @param string $resourceClass
- * @param string|null $operationName
- * @param mixed[] $context
- * @return bool
- */
- public function supports(string $resourceClass, string $operationName = null, array $context = []): bool
- {
- return DownloadRequest::class === $resourceClass;
- }
- /**
- * @param Operation $operation
- * @param mixed[] $uriVariables
- * @param mixed[] $context
- * @return Response|RedirectResponse
- * @throws FileNotFoundException
- */
- public function provide(Operation $operation, array $uriVariables = [], array $context = []): Response | RedirectResponse
- {
- if($operation instanceof GetCollection) {
- throw new RuntimeException('not supported', 500);
- }
- $id = $uriVariables['id'];
- $file = $this->fileRepository->find($id);
- if (empty($file)) {
- throw new RuntimeException("File " . $id . " does not exist; abort.");
- }
- if ($file->getStatus() !== FileStatusEnum::READY()->getValue()) {
- throw new RuntimeException("File " . $id . " has " . $file->getStatus() . " status; abort.");
- }
- // Read the file
- $token = $this->security->getToken();
- $content = $this->fileManager->read($file, $token);
- // Build the response and attach the file to it
- // @see https://symfony.com/doc/current/components/http_foundation.html#serving-files
- $response = new Response($content);
- $response->headers->set('Charset', 'UTF-8');
- $response->headers->set('Access-Control-Expose-Headers', 'Content-Disposition');
- if (!empty($file->getMimeType())) {
- $response->headers->set('Content-Type', $file->getMimeType());
- }
- $response->headers->set(
- 'Content-Disposition',
- HeaderUtils::makeDisposition(HeaderUtils::DISPOSITION_ATTACHMENT, $file->getName())
- );
- return $response;
- }
- }
|