ImageProvider.php 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. <?php
  2. declare(strict_types=1);
  3. namespace App\State\Provider\Core;
  4. use ApiPlatform\Metadata\GetCollection;
  5. use ApiPlatform\Metadata\Operation;
  6. use ApiPlatform\State\ProviderInterface;
  7. use App\Enum\Core\FileStatusEnum;
  8. use App\Repository\Core\FileRepository;
  9. use App\Service\File\Exception\FileNotFoundException;
  10. use App\Service\File\FileManager;
  11. use App\Service\Utils\FileUtils;
  12. use Symfony\Component\HttpFoundation\RedirectResponse;
  13. use Symfony\Component\HttpFoundation\Response;
  14. /**
  15. * Custom provider pour récupérer l'URL d'une image.
  16. */
  17. final class ImageProvider implements ProviderInterface
  18. {
  19. public function __construct(
  20. private readonly FileRepository $fileRepository,
  21. private readonly FileManager $fileManager,
  22. private readonly FileUtils $fileUtils,
  23. ) {
  24. }
  25. /**
  26. * @param array<mixed> $uriVariables
  27. * @param array<mixed> $context
  28. *
  29. * @throws FileNotFoundException
  30. */
  31. public function provide(Operation $operation, array $uriVariables = [], array $context = []): Response|RedirectResponse
  32. {
  33. if ($operation instanceof GetCollection) {
  34. throw new \RuntimeException('not supported', 500);
  35. }
  36. $uncropped =
  37. isset($context['filters']['uncropped']) &&
  38. ($context['filters']['uncropped'] === '1' || $context['filters']['uncropped'] === 'true');
  39. return $this->getImage($uriVariables['fileId'], $uriVariables['size'], $uncropped);
  40. }
  41. /**
  42. * @throws FileNotFoundException
  43. */
  44. protected function getImage(int $fileId, string $size, bool $uncropped = false): Response
  45. {
  46. $file = $this->fileRepository->find($fileId);
  47. if (empty($file)) {
  48. throw new \RuntimeException('Image '.$fileId.' does not exist; abort.');
  49. }
  50. if ($file->getStatus() !== FileStatusEnum::READY) {
  51. throw new \RuntimeException('Image '.$fileId.' has '.$file->getStatus().' status; abort.');
  52. }
  53. if (!$this->fileUtils->isImage($file)) {
  54. throw new \RuntimeException('File '.$fileId.' is not an image.');
  55. }
  56. $content = $this->fileManager->getImageUrl($file, $size, false, $uncropped);
  57. return new Response($content);
  58. }
  59. }