| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970 |
- <?php
- declare(strict_types=1);
- namespace App\State\Provider\Core;
- use ApiPlatform\Metadata\GetCollection;
- use ApiPlatform\Metadata\Operation;
- use ApiPlatform\State\ProviderInterface;
- use App\Enum\Core\FileStatusEnum;
- use App\Repository\Core\FileRepository;
- use App\Service\File\Exception\FileNotFoundException;
- use App\Service\File\FileManager;
- use App\Service\Utils\FileUtils;
- use Symfony\Component\HttpFoundation\RedirectResponse;
- use Symfony\Component\HttpFoundation\Response;
- /**
- * Custom provider pour récupérer l'URL d'une image.
- */
- final class ImageProvider implements ProviderInterface
- {
- public function __construct(
- private readonly FileRepository $fileRepository,
- private readonly FileManager $fileManager,
- private readonly FileUtils $fileUtils,
- ) {
- }
- /**
- * @param array<mixed> $uriVariables
- * @param array<mixed> $context
- *
- * @throws FileNotFoundException
- */
- public function provide(Operation $operation, array $uriVariables = [], array $context = []): Response|RedirectResponse
- {
- if ($operation instanceof GetCollection) {
- throw new \RuntimeException('not supported', 500);
- }
- $uncropped =
- isset($context['filters']['uncropped']) &&
- ($context['filters']['uncropped'] === '1' || $context['filters']['uncropped'] === 'true');
- return $this->getImage($uriVariables['fileId'], $uriVariables['size'], $uncropped);
- }
- /**
- * @throws FileNotFoundException
- */
- protected function getImage(int $fileId, string $size, bool $uncropped = false): Response
- {
- $file = $this->fileRepository->find($fileId);
- if (empty($file)) {
- throw new \RuntimeException('Image '.$fileId.' does not exist; abort.');
- }
- if ($file->getStatus() !== FileStatusEnum::READY) {
- throw new \RuntimeException('Image '.$fileId.' has '.$file->getStatus().' status; abort.');
- }
- if (!$this->fileUtils->isImage($file)) {
- throw new \RuntimeException('File '.$fileId.' is not an image.');
- }
- $content = $this->fileManager->getImageUrl($file, $size, false, $uncropped);
- return new Response($content);
- }
- }
|