src/Controller/ArticleController.php line 51

Open in your IDE?
  1. <?php
  2. // src/Controller/LuckyController.php
  3. namespace App\Controller;
  4. use Symfony\Component\HttpFoundation\Response;
  5. use Symfony\Component\HttpFoundation\Request;
  6. use Symfony\Component\Routing\Annotation\Route;
  7. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  8. use Symfony\Contracts\Translation\TranslatorInterface;
  9. use Symfony\Component\Validator\Validator\ValidatorInterface;
  10. use Symfony\Component\HttpFoundation\Cookie;
  11. use Symfony\Component\HttpFoundation\RedirectResponse;
  12. use Symfony\Component\HttpKernel\KernelInterface;
  13. use Sensio\Bundle\FrameworkExtraBundle\Configuration\IsGranted;
  14. use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
  15. use FOS\RestBundle\Request\ParamFetcherInterface;
  16. use FOS\RestBundle\Controller\Annotations\QueryParam;
  17. use Symfony\Component\String\Slugger\SluggerInterface;
  18. use Doctrine\ORM\EntityManagerInterface;
  19. use App\Entity\Article;
  20. use App\Form\ArticleType;
  21. class ArticleController extends AbstractController
  22. {
  23.     protected $em;
  24.     
  25.     public function __construct(EntityManagerInterface $em){
  26.         $this->em $em;
  27.     }
  28.     /**
  29.     * @Route({
  30.      *     "en": "/press",
  31.      *     "es": "/prensa",
  32.      *     "de": "/presse",
  33.      *     "fr": "/presse_fr",
  34.      *     "it": "/stampa",
  35.      *     "pt": "/imprensa",
  36.      *     "cn": "/press_cn",
  37.      *     "cn2": "/press_cn2",
  38.      * }, name="articles_list")
  39.      * @QueryParam(name="page", requirements="\d+", default=1, description="Page number.")
  40.      * @QueryParam(name="sort", requirements="e.iccid|u.amountGb|u.priceValue|u.reference|u.createdAt|u.transactedAt|us.lastName|u.customerSubscription|rp.amountGb|rp.priceValue", description="Sort.")
  41.      * @QueryParam(name="dir", requirements="asc|desc", default="asc", description="Sort direction.")         
  42.      * @QueryParam(name="q", requirements=".*", default="", nullable=true, description="Q.")         
  43.      * @QueryParam(name="country", requirements="\d+", default=null, nullable=true, strict=true, description="Country.")         
  44.      */    
  45.     public function index(Request $requestParamFetcherInterface $paramFetcher)
  46.     {
  47.         // parameters
  48.         $page $paramFetcher->get('page');
  49.         $sort $paramFetcher->get('sort');
  50.         $dir $paramFetcher->get('dir');
  51.         $q $paramFetcher->get('q');
  52.         $country $paramFetcher->get('country');
  53.         $download $request->query->get('download');    
  54.         // query
  55.         $results_per_page $this->getParameter('app.results_per_page');        
  56.         // filters
  57.         $currentFilters = [];
  58.         if($sort){
  59.             $currentFilters['sort'] = $sort;
  60.             $currentFilters['dir'] = $dir;          
  61.         } 
  62.         $currentFilters['q'] = $q;
  63.         $repo $this->em->getRepository(Article::class);
  64.         $articles $repo->getList($q$sort$dir$page$results_per_page$request->getLocale(), $country);
  65.         $response $this->render('jelly/articles/index.html.twig', [
  66.             'articles' => $articles,
  67.             'currentFilters' => $currentFilters,
  68.         ]);
  69.         return $response;
  70.     }
  71.     /**
  72.     * @Route({
  73.      *     "en": "/press/{slug}",
  74.      *     "es": "/prensa/{slug}",
  75.      *     "de": "/presse/{slug}",
  76.      *     "fr": "/presse_fr/{slug}",
  77.      *     "it": "/stampa/{slug}",
  78.      *     "pt": "/imprensa/{slug}",
  79.      *     "cn": "/press_cn/{slug}",
  80.      *     "cn2": "/press_cn2/{slug}",
  81.      * }, name="article_detail")
  82.      */    
  83.     public function detail(Request $requestParamFetcherInterface $paramFetcherstring $slug)
  84.     {
  85.         $repo $this->em->getRepository(Article::class);
  86.         // query
  87.         $results_per_page $this->getParameter('app.results_per_page');        
  88.         $article $repo->findOneBy(['slug' => $slug]);
  89.         $articles $repo->getList(nullnullnull1$results_per_page$request->getLocale(), $article->getCountry());
  90.         if(!$article)
  91.             throw $this->createNotFoundException('Article not found');
  92.         $article->setTranslatableLocale($request->getLocale());
  93.         $this->em->refresh($article);
  94.         $response $this->render('jelly/articles/detail.html.twig', [
  95.             'articles' => $articles,
  96.             'article' => $article,
  97.         ]);
  98.         return $response;
  99.     }
  100.     /**
  101.     * @Route("/admin/content/articles", name="admin_articles_list")
  102.     * @IsGranted("ROLE_ADMIN")
  103.      */    
  104.     public function indexAdmin(Request $requestParamFetcherInterface $paramFetcher)
  105.     {
  106.         $repo $this->getDoctrine()->getRepository(Article::class);
  107.         
  108.         $articles $repo->getList();
  109.         return $this->render('angle/articles/index.html.twig', [
  110.             'articles' => $articles,
  111.         ]);     
  112.     }
  113.     /**
  114.     * @Route("/admin/article/{articleId}", name="admin_article_detail", methods={"GET","HEAD", "POST"})
  115.     * @Route("/admin/article/", name="admin_article_new", methods={"GET","HEAD","POST"})
  116.     * @IsGranted("ROLE_ADMIN")
  117.      */
  118.     public function detailAdmin(ParamFetcherInterface $paramFetcherRequest $requestKernelInterface $appKernelSluggerInterface $slugger, ?string $articleId null ): Response
  119.     {
  120.         $em $this->getDoctrine()->getManager();
  121.         $repo $this->getDoctrine()->getManager()->getRepository(Article::class);
  122.         
  123.         $article null;
  124.         if($articleId){
  125.             $article $repo->find($articleId);
  126.             $article->setTranslatableLocale($request->getSession()->get('locale'));
  127.             $em->refresh($article);
  128.             if(!$article)
  129.                 throw $this->createNotFoundException("Article not found");
  130.         }
  131.         $form $this->createForm(ArticleType::class, $article);
  132.         $form->handleRequest($request);
  133.         if ($form->isSubmitted() ) {
  134.             $article $form->getData();
  135.             if ($form->isValid()){  
  136.                 if(!$articleId){
  137.                     $article->setImage('');
  138.                     $slugIndex 0;
  139.                     do {
  140.                         $slug strtolower($slugger->slug($article->getTitle())) . ($slugIndex "-{$slugIndex}"");
  141.                         $existingArticle $repo->findOneBy(['slug' => $slug]);
  142.                         $slugIndex++;
  143.                     } while ($existingArticle != null);
  144.                     $article->setSlug($slug);
  145.                 }                
  146.                 $imageList $form->get('imageList')->getData();
  147.                 if ($imageList) {
  148.                     $imagePath $appKernel->getProjectDir() . "/public/imgs/articles/{$article->getSlug()}.jpg";
  149.                     \imagejpeg(\imagecreatefromstring(\file_get_contents($imageList->getRealPath())), $imagePath );
  150.                 }
  151.                 $image $form->get('image')->getData();
  152.                 if ($image) {
  153.                     $imagePath $appKernel->getProjectDir() . "/public/imgs/articles/{$article->getSlug()}_full.jpg";
  154.                     \imagejpeg(\imagecreatefromstring(\file_get_contents($image->getRealPath())), $imagePath );
  155.                 }                
  156.                 $article->setImage($article->getSlug());
  157.                 if(!$article->getPublishedAt()){
  158.                     $article->setPublishedAt(new \DateTime());
  159.                 }
  160.                 $em->persist($article);
  161.                 $em->flush();
  162.                    
  163.                 return $this->redirectToRoute('admin_articles_list');
  164.             }
  165.         }
  166.        return $this->render('angle/articles/detail.html.twig', [
  167.             'form' => $form->createView(),
  168.             'article' => $article,
  169.         ]);
  170.     }    
  171.      /**
  172.      * @IsGranted("ROLE_ADMIN")
  173.      * @Route(
  174.      *    "/services/article.{_format}", 
  175.      *     name="article_delete",
  176.      *     requirements={
  177.      *         "_format": "json"
  178.      *     },
  179.      *     methods={"DELETE"}
  180.      * )
  181.      */
  182.     public function delete(Request $request)
  183.     {        
  184.      
  185.         $repository $this->getDoctrine()->getRepository(Article::class);
  186.         $id $request->query->get('id');
  187.         
  188.         if($id){
  189.             $entity $repository->findOneById($id);
  190.             
  191.             $em $this->getDoctrine()->getManager();
  192.             $em->remove($entity);
  193.             $em->flush();
  194.         }
  195.         return ['ok' => true];
  196.     }    
  197. }