src/Controller/ProductsController.php line 26

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. use App\Entity\Products;
  4. use App\Repository\ContactRepository;
  5. use App\Repository\TarifsRepository;
  6. use Doctrine\ORM\EntityManagerInterface;
  7. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  8. use Symfony\Component\HttpFoundation\Response;
  9. use Symfony\Component\Routing\Annotation\Route;
  10. use Symfony\Component\String\Slugger\SluggerInterface;
  11. use Symfony\Component\HttpFoundation\BinaryFileResponse;
  12. use Symfony\Component\HttpFoundation\ResponseHeaderBag;
  13. #[Route('/produits'name'products_')]
  14. class ProductsController extends AbstractController
  15. {
  16.     #[Route('/'name'index')]
  17.     public function index(): Response
  18.     {
  19.         return $this->render('products/index.html.twig');
  20.     }
  21.     #[Route('/{slug}'name'details')]
  22.     public function details(Products $productContactRepository $contactRepositoryTarifsRepository $tarifsRepository): Response
  23.     {
  24.         $user $this->getUser();
  25.         // Sécurité : si personne n'est connecté
  26.         //if (!$user) {
  27.         //    return $this->redirectToRoute('app_login');
  28.         //}
  29.         // On récupère les contacts ayant le même email
  30.         $contacts = [];
  31.         if ($user) {
  32.             $contacts $contactRepository->findBy(['email' => $user->getEmail()]);
  33.         }
  34.         // Récupère tous les tarifs (ou filtre selon ton besoin)
  35.         $tarifs $tarifsRepository->findBy(['referenceArticle' => $product->getSlug()]);
  36.         // On check si c'est un accessoire et si c'est la cas on recherche les produits liés
  37.         $productsSources $product->getAccessoriesSources();
  38.         return $this->render('products/details.html.twig', [
  39.             'product' => $product,
  40.             'user' => $user,
  41.             'contacts' => $contacts,
  42.             'tarifs' => $tarifs,
  43.             'productsSources' => $productsSources,
  44.         ]);
  45.     }
  46.     #[Route('/image/{slug}'name'mainImage')]
  47.     public function mainImage(Products $productstring $slug): Response
  48.     {
  49.         if ($product) {
  50.             $mainImage $product->getImages()->get(0);
  51.             $urlImage $mainImage $mainImage->getName() : null;
  52.             if ($urlImage) {
  53.                 $filePath __DIR__ '/../../public/assets/uploads/products/' $urlImage;
  54.                 // Vérifiez si le fichier existe
  55.                 if (file_exists($filePath)) {
  56.                     // Obtenez le type MIME du fichier
  57.                     $mimeType mime_content_type($filePath);
  58.                     // Vérifiez si le fichier est une image
  59.                     if (str_starts_with($mimeType'image/')) {
  60.                         // Obtenez l'extension à partir du type MIME
  61.                         $extension = match ($mimeType) {
  62.                             'image/jpeg' => 'jpg',
  63.                             'image/png' => 'png',
  64.                             'image/gif' => 'gif',
  65.                             'image/webp' => 'webp',
  66.                             default => null,
  67.                         };
  68.                         if ($extension) {
  69.                             // Chargez l'image avec GD
  70.                             $image = match ($extension) {
  71.                                 'jpg' => imagecreatefromjpeg($filePath),
  72.                                 'png' => imagecreatefrompng($filePath),
  73.                                 'gif' => imagecreatefromgif($filePath),
  74.                                 'webp' => imagecreatefromwebp($filePath),
  75.                                 default => null,
  76.                             };
  77.                             if ($image) {
  78.                                 // Vérifiez les dimensions
  79.                                 $width imagesx($image);
  80.                                 $height imagesy($image);
  81.                                 // Taille cible minimale
  82.                                 $targetWidth 1200;
  83.                                 $targetHeight 1200;
  84.                                 // Calculer les nouvelles dimensions en respectant les proportions
  85.                                 $scaleFactor max($targetWidth $width$targetHeight $height);
  86.                                 $newWidth = (int) ceil($width $scaleFactor);
  87.                                 $newHeight = (int) ceil($height $scaleFactor);
  88.                                 if ($newWidth $width || $newHeight $height) {
  89.                                     // Redimensionner l'image en respectant les proportions
  90.                                     $resizedImage imagecreatetruecolor($newWidth$newHeight);
  91.                                     // Conserver la transparence pour les PNG et GIF
  92.                                     if ($extension === 'png' || $extension === 'gif') {
  93.                                         imagecolortransparent($resizedImageimagecolorallocatealpha($resizedImage000127));
  94.                                         imagealphablending($resizedImagefalse);
  95.                                         imagesavealpha($resizedImagetrue);
  96.                                     }
  97.                                     // Redimensionner avec GD
  98.                                     imagecopyresampled(
  99.                                         $resizedImage,
  100.                                         $image,
  101.                                         0000,
  102.                                         $newWidth,
  103.                                         $newHeight,
  104.                                         $width,
  105.                                         $height
  106.                                     );
  107.                                     // Remplacez l'image originale par l'image redimensionnée
  108.                                     $image $resizedImage;
  109.                                 }
  110.                                 // Si l'image est en WebP, convertissez-la en JPEG
  111.                                 $isWebP $extension === 'webp';
  112.                                 if ($isWebP) {
  113.                                     $extension 'jpg';
  114.                                     $mimeType 'image/jpeg';
  115.                                 }
  116.                                 // Enregistrez l'image temporairement
  117.                                 $tempFilePath sys_get_temp_dir() . '/' uniqid($slugtrue) . '.' $extension;
  118.                                 match ($extension) {
  119.                                     'jpg' => imagejpeg($image$tempFilePath100), // Qualité maximale
  120.                                     'png' => imagepng($image$tempFilePath),
  121.                                     'gif' => imagegif($image$tempFilePath),
  122.                                 };
  123.                                 // Libérez la mémoire
  124.                                 imagedestroy($image);
  125.                                 // Générez le nom de fichier avec le slug et l'extension
  126.                                 $fileName $slug '.' $extension;
  127.                                 $response = new BinaryFileResponse($tempFilePath);
  128.                                 $response->headers->set('Content-Type'$mimeType);
  129.                                 $response->setContentDisposition(
  130.                                     ResponseHeaderBag::DISPOSITION_INLINE// ou ATTACHMENT pour forcer le téléchargement
  131.                                     $fileName
  132.                                 );
  133.                                 return $response;
  134.                             } else {
  135.                                 return new Response('Impossible de charger l\'image.'Response::HTTP_INTERNAL_SERVER_ERROR);
  136.                             }
  137.                         } else {
  138.                             return new Response('Type d\'image non supporté.'Response::HTTP_UNSUPPORTED_MEDIA_TYPE);
  139.                         }
  140.                     } else {
  141.                         return new Response('Le fichier n\'est pas une image.'Response::HTTP_UNSUPPORTED_MEDIA_TYPE);
  142.                     }
  143.                 }
  144.             }
  145.         }
  146.         return new Response('Image non trouvée'Response::HTTP_NOT_FOUND);
  147.     }
  148. }