src/Controller/CategoryController.php line 37

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. use App\Entity\Article;
  4. use App\Entity\Category;
  5. use App\Entity\Channel;
  6. use App\Entity\Media;
  7. use App\Entity\StripeProduct;
  8. use App\Entity\Card;
  9. use App\Service\ArticleEntityService;
  10. use App\Service\CategoryEntityService;
  11. use App\Service\MediaEntityService;
  12. use App\Service\StripeService;
  13. use Bluesquare\ValidatorBundle\Validator;
  14. use Doctrine\ORM\EntityManagerInterface;
  15. use Http\Client\Exception;
  16. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  17. use Symfony\Component\DependencyInjection\ContainerInterface;
  18. use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
  19. use Symfony\Component\HttpFoundation\Cookie;
  20. use Symfony\Component\HttpFoundation\ParameterBag;
  21. use Symfony\Component\HttpFoundation\Request;
  22. use Symfony\Component\HttpFoundation\Response;
  23. use Symfony\Component\Routing\Annotation\Route;
  24. class CategoryController extends AbstractController
  25. {
  26.     private ParameterBagInterface $parameterBag;
  27.     public function __construct(ParameterBagInterface $parameterBag)
  28.     {
  29.         $this->parameterBag $parameterBag;
  30.     }
  31.     /**
  32.      * @Route("/actualite/{slug}/{page}", name="category.view", defaults={"page"=1})
  33.      */
  34.     public function index(Validator $validator,Request $requestArticleEntityService $articleServiceEntityManagerInterface $managerCategoryEntityService $categoryService$slug$page,StripeService $stripeService)
  35.     {
  36.         $old_storage_url=$this->parameterBag->get('storage_url');
  37.         $old_storage_url str_replace('http://'''$old_storage_url);
  38.         $new_storage_url=$this->parameterBag->get('storage_url_front');
  39.         $new_storage_url str_replace('http://'''$new_storage_url);
  40.             $category $categoryService->getBySlug($slug);
  41.         if (!$category || !($category instanceof Category))
  42.             throw $this->createNotFoundException();
  43.         $channel $manager->getRepository(Channel::class)->findOneBy(['active' => true]);
  44.         if (!$channel) throw $this->createNotFoundException();
  45.         $articleRepository $manager->getRepository(Article::class);
  46.         $page intval($page);
  47.         $page max(1$page);
  48.         $limit 50;
  49.         $highlightedArticlesIDS = [];
  50.         $highlights $articleService->formatAll($articleRepository->getHighlightedArticles($channel5$category));
  51.         foreach ($highlights as $highlight){
  52.              array_push($highlightedArticlesIDS$highlight['id']);
  53.         }
  54.         $recent_articles $articleService->formatAll($articleRepository->getRecentArticles($highlightedArticlesIDS,$category3));
  55.         foreach ($recent_articles as $recent){
  56.             array_push($highlightedArticlesIDS$recent['id']);
  57.         }
  58.         $articles $articleService->formatAll($articleRepository->getALLCategoryArticles($highlightedArticlesIDS$category5$page));
  59.         $count_articles intval($articleRepository->countCategoryArticles($category));
  60.         $pages_number ceil($count_articles/$limit);
  61.         $isLastPage $page == $pages_number;
  62.         $user=$this->getUser();
  63.         $productSort=[];
  64.         $products =  $manager->getRepository(StripeProduct::class)->getMagazines();
  65.         $products array_slice($products04true);
  66.         $httpClient = \Symfony\Component\HttpClient\HttpClient::create();
  67.         foreach ($products as  $k => $product){
  68.             $products[$k]['url_front'] = '';
  69.             $url =  $product['file']."_mobile_298_406";
  70.             $old_url $product['file'] ;
  71.             $response $httpClient->request('HEAD'$url);
  72.             $statusCode $response->getStatusCode();
  73.             if ($statusCode === 200) {
  74.                 $products[$k]['url'] = $url;
  75.             }else{
  76.                 $products[$k]['url'] = $old_url;
  77.             }
  78.             if(str_contains($products[$k]['url'],$old_storage_url)) {
  79.                 $url_front str_replace($old_storage_url,$new_storage_url,$products[$k]['url']);
  80.                 $products[$k]['url_front'] = $url_front;
  81.             }
  82.         }
  83.         $subscriptionStatus=$stripeService->getSubscriptionStatus($this->getUser());
  84.         if ($request->isXmlHttpRequest()) {
  85.             $articles $articleService->formatAll($articleRepository->getALLCategoryArticles($highlightedArticlesIDS$category$page*51));
  86.             return $this->render('themes/theme-5/article/all-articles.html.twig', [
  87.                 'validator' => $validator,
  88.                 'highlighted' => $highlights,
  89.                 'articles' => $articles,
  90.                 'category' => $category,
  91.                 'page' => $page,
  92.                 'is_last_page' => $isLastPage,
  93.                 'products' => $products,
  94.                 'userSubscriptionsStatus'=>$subscriptionStatus,
  95.         
  96.             ]);
  97.         }
  98.         return $this->render('category/category.html.twig', [
  99.             'validator' => $validator,
  100.             'highlighted' => $highlights,
  101.             'articles' => $articles,
  102.             'category' => $category,
  103.             'page' => $page,
  104.             'is_last_page' => $isLastPage,
  105.             'products' => $products,
  106.             'userSubscriptionsStatus'=>$subscriptionStatus,
  107.             'recent_articles' =>$recent_articles,
  108.         ]);
  109.     }
  110.     /**
  111.      * @Route("/actual/{slug}/{page}", name="sous-category.view" , defaults={"page"=1}))
  112.      */
  113.     public function show(Validator $validator,Request $requestArticleEntityService $articleServiceEntityManagerInterface $managerCategoryEntityService $categoryService$slug$page,StripeService $stripeService)
  114.     {
  115.         $old_storage_url=$this->parameterBag->get('storage_url');
  116.         $old_storage_url str_replace('http://'''$old_storage_url);
  117.         $new_storage_url=$this->parameterBag->get('storage_url_front');
  118.         $new_storage_url str_replace('http://'''$new_storage_url);
  119.         $category $categoryService->getBySlug($slug);
  120.         if (!$category || !($category instanceof Category))
  121.             throw $this->createNotFoundException();
  122.         $channel $manager->getRepository(Channel::class)->findOneBy(['active' => true]);
  123.         if (!$channel) throw $this->createNotFoundException();
  124.         $articleRepository $manager->getRepository(Article::class);
  125.         $page intval($page);
  126.         $page max(1$page);
  127.         $limit 50;
  128.         $highlights $articleService->formatAll($articleRepository->getHighlightedArticles($channel5$category));
  129.         $countHighliteted count($highlights);
  130.         $key 0;
  131.         if($countHighliteted 3) {
  132.             $key = ($countHighliteted) ;
  133.         }
  134.         elseif ($countHighliteted == 0){
  135.             $key $countHighliteted;
  136.         }
  137.         $articles $articleService->formatAll($articleRepository->getCategoryArticles($category7+$key$page));
  138.         $count_articles intval($articleRepository->countCategoryArticles($category));
  139.         $pages_number ceil($count_articles/$limit);
  140.         $isLastPage $page == $pages_number;
  141.         $user=$this->getUser();
  142.         $productSort=[];
  143.         $products =  $manager->getRepository(StripeProduct::class)->getMagazines();
  144.         $products array_slice($products04true);
  145.         $httpClient = \Symfony\Component\HttpClient\HttpClient::create();
  146.         foreach ($products as  $k => $product){
  147.             $products[$k]['url_front'] = '';
  148.             $url =  $product['file']."_mobile_298_406";
  149.             $old_url $product['file'] ;
  150.             $response $httpClient->request('HEAD'$url);
  151.             $statusCode $response->getStatusCode();
  152.             if ($statusCode === 200) {
  153.                 $products[$k]['url'] = $url;
  154.             }else{
  155.                 $products[$k]['url'] = $old_url;
  156.             }
  157.             if(str_contains($products[$k]['url'],$old_storage_url)) {
  158.                 $url_front str_replace($old_storage_url,$new_storage_url,$products[$k]['url']);
  159.                 $products[$k]['url_front'] = $url_front;
  160.             }
  161.         }
  162.         $subscriptionStatus=$stripeService->getSubscriptionStatus($this->getUser());
  163.         if ($request->isXmlHttpRequest()) {
  164.             $articles $articleService->formatAll($articleRepository->getCategoryArticles($category$page*(6+$key), 1));
  165.             return $this->render('themes/theme-5/article/all-articles-sous.html.twig', [
  166.                 'startAt' =>$key,
  167.                 'validator' => $validator,
  168.                 'highlighted' => $highlights,
  169.                 'articles' => $articles,
  170.                 'category' => $category,
  171.                 'page' => $page,
  172.                 'is_last_page' => $isLastPage,
  173.                 'products' => $products,
  174.                 'userSubscriptionsStatus'=>$subscriptionStatus,
  175.             ]);
  176.         }
  177.         return $this->render('category/sous-category.html.twig', [
  178.             'start' =>$key,
  179.             'startAt' =>$key,
  180.             'type' =>'sous-category',
  181.             'validator' => $validator,
  182.             'highlighted' => $highlights,
  183.             'articles' => $articles,
  184.             'category' => $category,
  185.             'page' => $page,
  186.             'is_last_page' => $isLastPage,
  187.              'products' => $products,
  188.             'userSubscriptionsStatus'=>$subscriptionStatus,
  189.         ]);
  190.     }
  191.     /**
  192.      * @Route("/abonn", name="abonn" )
  193.      */
  194.     public function abonn()
  195.     {
  196.         return $this->render('category/abonne.html.twig');
  197.     }
  198.     /**
  199.      * @Route ("videos-podcast", name="video-podcast")
  200.      */
  201.     public function getVideoPodcast(Validator $validator,Request $requestArticleEntityService $articleServiceEntityManagerInterface $managerCategoryEntityService $categoryService,StripeService $stripeService){
  202.         $channel $manager->getRepository(Channel::class)->findOneBy(['active' => true]);
  203.         $articleRepository $manager->getRepository(Article::class);
  204.         $videoPodcast =$articleService->formatAll($articleRepository->getArticlesVideoAndPodcasts());
  205.         $highlighted =$articleService->formatAll($articleRepository->getHighlightedArticlesVideoAndPodcasts6));
  206.         $latest array_slice($videoPodcast,0,3);
  207.         $articles array_slice($videoPodcast,4);
  208.         $video = [];
  209.         $Podcast = [];
  210.         foreach ($articles as $art ){
  211.             foreach ($art["categories"] as $cat){
  212.                 if ($cat['name'] == "Vidéos"){
  213.                     $video[] = $art ;
  214.                 }elseif($cat['name'] == "Podcasts"){
  215.                     $Podcast[] = $art ;
  216.                 }
  217.             }
  218.         }
  219.         $countVideo count($video);
  220.         $countPodcast count($Podcast);
  221.         $countArticles max($countVideo$countPodcast);
  222.         $limit null;
  223.         $isReach false;
  224.         if ($request->isXmlHttpRequest()) {
  225.             $limit $request->get('limit');
  226.             $offset $limit 3;
  227.             $articlePodcast array_slice($Podcast,$offset3);
  228.             $articleVideo array_slice($video,$offset3);
  229.             //dd($articleVideo, $articlePodcast);
  230.             if ($limit >= $countArticles){
  231.                 $isReach true;
  232.             }
  233.             return $this->render(
  234.                 "themes/theme-5/article/_partials/videopodcast-preview.html.twig",
  235.                 [
  236.                     'podcasts' => $articlePodcast,
  237.                     'videos' => $articleVideo,
  238.                     'isReach' => $isReach,
  239.                 ]
  240.             );
  241.         }
  242.         $articleVideo array_slice($video,03);
  243.         $articlePodcast array_slice($Podcast,03);
  244.         return $this->render(
  245.             "article/videospodcast.html.twig",
  246.             [
  247.                 'articles' => $latest,
  248.                 'highlighted' => $highlighted,
  249.                 'videos' => $articleVideo,
  250.                 'podcasts' => $articlePodcast,
  251.                 'isReach' => false,
  252.             ]
  253.         );
  254.     }
  255.     /**
  256.      * @Route ("/generateWebpImages", name="video-podcast.show")
  257.      */
  258.     public function generateWebpImages(EntityManagerInterface $entityManager,ContainerInterface $container,MediaEntityService $entityService){
  259.         set_time_limit(1200000);
  260.         session_start();
  261.         $temp_dir $container->get('kernel')->getProjectDir().'/var/temp';
  262.         $mediaRepository $entityManager->getRepository(Media::class);
  263.         $medias $mediaRepository->activedImages();
  264. //        $medias = array_slice($medias, 0, 100);
  265.         /** @var Media $media */
  266.         foreach ($medias as $media) {
  267.             $file $media->getOriginalFile() ? $media->getOriginalFile() : $media->getFile();
  268.             if ($this->getParameter("storage_path") && !empty($this->getParameter("storage_path"))) {
  269.                 $path $this->getParameter('storage_url') . "/" $this->getParameter("storage_path") . "/media/" $file;
  270.             } else {
  271.                 $path $this->getParameter('storage_url') . "/media/" $file;
  272.             }
  273.             $path trim($path);
  274.             if(str_contains($file,'.')){
  275.                 $extension explode('.'$file)[1];
  276.             }else{
  277.                 if ($media->getType()=="image/jpeg"){
  278.                     $extension "jpeg";
  279.                 }else{
  280.                     $extension explode('/'$media->getType())[1];
  281.                 }
  282.             }
  283.             $randomBytes_original random_bytes(4); // 7 octets (14 caractères hexadécimaux)
  284.             $randomHash_original bin2hex($randomBytes_original);
  285.             $file_original=$temp_dir."/".$randomHash_original."-".$randomHash_original.".".$extension;
  286.             try {
  287.                 $content file_get_contents($path);
  288.                 if ($content !== false) {
  289.                     file_put_contents($file_original$content);
  290.                 }
  291.             }catch (\Exception $e) {
  292.                 echo "An error occurred for $path: " $e->getMessage() . "\n";
  293.                 continue;
  294.             }
  295.             $randomBytes random_bytes(4); // 7 octets (14 caractères hexadécimaux)
  296.             $randomHash bin2hex($randomBytes);
  297.             $webpFilePath $temp_dir "/" $randomHash "-" $randomHash".webp";
  298.             $types = ['image/jpeg''image/png'];
  299.             $originalImage null;
  300.             if (in_array($media->getType(), $types)) {
  301.                 if ($media->getType() == 'image/jpeg') {
  302.                     try {
  303.                         $originalImage imagecreatefromjpeg($path);
  304.                         if (!$originalImage) {
  305.                             continue;
  306.                         }
  307.                     } catch (\Exception $e) {
  308.                         echo "An error occurred for $path: " $e->getMessage() . "\n";
  309.                         continue;
  310.                     }
  311.                 } elseif ($media->getType() == 'image/png') {
  312.                     try {
  313.                         $originalImage imagecreatefrompng($path);
  314.                         if (!$originalImage) {
  315.                             continue;
  316.                         }
  317.                     } catch (\Exception $e) {
  318.                         echo "An error occurred for $path: " $e->getMessage() . "\n";
  319.                         continue;
  320.                     }
  321.                 }
  322.             }
  323.             if ($originalImage) {
  324.                 if($media->getType() == 'image/png'){
  325.                     try {
  326.                         $sourceImage imagecreatefrompng($path);
  327.                         if ($sourceImage) {
  328.                             $rgbImage imagecreatetruecolor(imagesx($sourceImage), imagesy($sourceImage));
  329.                             imagecopy($rgbImage$sourceImage0000imagesx($sourceImage), imagesy($sourceImage));
  330.                             imagewebp($rgbImage$webpFilePath,50);
  331.                         }
  332.                     } catch (\Exception $e) {
  333.                         $error=$error+1;
  334.                         continue;
  335.                     }
  336.                 }
  337.                 else{
  338.                     imagewebp($originalImage$webpFilePath,50);
  339.                 }
  340.                 try {
  341.                     $webpData file_get_contents($webpFilePath);
  342.                     if ($webpData !== false) {
  343.                         $webpImage imagecreatefromwebp('data://image/webp;base64,' base64_encode($webpData));
  344.                     }
  345.                 }catch (\Exception $e) {
  346.                     $error=$error+1;
  347.                     continue;
  348.                 }
  349.                 if ($webpImage !== false) {
  350.                     // Get the width and height
  351.                     $this->setOriginalValues($media,$webpImage);
  352.                     $entityManager->persist($media);
  353.                     $uploadedFile = new \Symfony\Component\HttpFoundation\File\UploadedFile(
  354.                         $webpFilePath,
  355.                         basename($webpFilePath),
  356.                         mime_content_type($webpFilePath),
  357.                         filesize($webpFilePath),
  358.                         false,
  359.                         true
  360.                     );
  361.                     $uploadedFileOriginal = new \Symfony\Component\HttpFoundation\File\UploadedFile(
  362.                         $file_original,
  363.                         basename($file_original),
  364.                         mime_content_type($file_original),
  365.                         filesize($file_original),
  366.                         false,
  367.                         true
  368.                     );
  369.                     $entityService->postValidateThumbnail($media$uploadedFile$uploadedFileOriginal,true);
  370.                     $entityManager->persist($media);
  371.                     $entityManager->flush();
  372.                     @unlink($file);
  373.                 }
  374.             }
  375.             $cover $entityService->format($media);
  376.         }
  377.     }
  378.     public function setOriginalValues($media,$webpImage){
  379.         $width imagesx($webpImage);
  380.         $height imagesy($webpImage);
  381.         $media->setOriginalThumbnail($media->getThumbnail());
  382.         $media->setOriginalWidth($media->getWidth());
  383.         $media->setOriginalHeight($media->getHeight());
  384.         $media->setOriginalType($media->getType());
  385.         $media->setOriginalFile($media->getFile());
  386.         $media->setOriginalFilename($media->getFilename());
  387.         $media->setWidth($width);
  388.         $media->setHeight($height);
  389.     }
  390. }