src/Controller/StructureController.php line 100

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  4. use Symfony\Component\Routing\Annotation\Route;
  5. use Symfony\Component\HttpFoundation\Request;
  6. use Symfony\Component\HttpFoundation\JsonResponse;
  7. use App\Entity\QuestionAnswer;
  8. use App\Entity\Structure;
  9. use App\Entity\Tag;
  10. use App\Entity\Theme;
  11. use Knp\Component\Pager\PaginatorInterface;
  12. class StructureController extends AbstractController
  13. {
  14.     /**
  15.      * @Route("/structure/{id}", name="showStructure", requirements={"id"="\d+"})
  16.      */
  17.     public function showStructure(Request $request$id)
  18.     {
  19.         $structure $this->getDoctrine()->getRepository(Structure::class)->find($id);
  20.         if (!$structure) {
  21.             throw $this->createNotFoundException('Pas de structure avec l\'id ' $id '.');
  22.             // the above is just a shortcut for:
  23.             // throw new NotFoundHttpException('The product does not exist');
  24.         }
  25.         if (!$structure->getPublished()) {
  26.             $redirectUrl $this->_notPublished($request);
  27.             if($redirectUrl) return $this->redirect($redirectUrl);
  28.         }
  29.         $slug $structure->getSlug();
  30.         if($slug && $slug !== "") {
  31.             return $this->redirect($this->generateUrl('showStructureBySlug', ['slug' => $slug]));
  32.         } else {
  33.             return $this->render('structure/show.html.twig', [
  34.                 'structure' => $structure
  35.             ]);
  36.         }
  37.     }
  38.     
  39.     /**
  40.      * @Route("/structure/{slug}", name="showStructureBySlug")
  41.      */
  42.     public function showStructureBySlug(Request $request$slug)
  43.     {
  44.         $structure $this->getDoctrine()->getRepository(Structure::class)->findOneBySlug($slug);
  45.         if (!$structure) {
  46.             throw $this->createNotFoundException('Pas de structure avec le slug "' $slug '".');
  47.         }
  48.         if (!$structure->getPublished()) {
  49.             $redirectUrl $this->_notPublished($request);
  50.             if($redirectUrl) return $this->redirect($redirectUrl);
  51.         }
  52.         return $this->render('structure/show.html.twig', [
  53.             'structure' => $structure
  54.         ]);
  55.     }
  56.     /**
  57.      * action if entity not published
  58.      * @return string $redirectUrl
  59.      */
  60.     private function _notPublished($request) {
  61.         if(!$this->isGranted('ROLE_ADMIN')) {
  62.             $requestUri $request->getRequestUri();
  63.             $baseUrl $request->getSchemeAndHttpHost();
  64.             $this->addFlash(
  65.                 'error-popup',
  66.                 'L\'url demandée : "' $baseUrl $requestUri '" n\'existe pas.'
  67.             );
  68.             $referer $request->headers->get('referer');
  69.             if(null != $referer && substr($referer0strlen($baseUrl)) === $baseUrl) {
  70.                 // on retourne de là oú l'on vient, si l'on vient de ce site
  71.                 $redirectUrl substr($refererstrlen($baseUrl));
  72.             } else {
  73.                 // pas de referer trouvé ou appel depuis site extérieur, on va donc à la home
  74.                 $redirectUrl $this->generateUrl('home');
  75.             }
  76.             
  77.         } else { 
  78.             // rôle admin, on laisse consulter
  79.             $this->addFlash(
  80.                 'notice',
  81.                 'Cette structure n\'est pas publiée. En tant qu\'admin vous pouvez toutefois la voir.'
  82.             );
  83.             $redirectUrl null;
  84.         }
  85.         return $redirectUrl;
  86.     }
  87.     
  88.     /**
  89.      * @Route("/structure/teasers/{ids}", name="showSearchResult")
  90.      * @param string $ids liste d'ids séparées par des tirets 
  91.      * @param bool $listWithThumbnails si on veut afficher une liste d'images, sinon liste textuelle 
  92.      */
  93.     public function showSearchResult($ids$listWithThumbnails false)
  94.     {
  95.         $ids explode("-"$ids); // $ids devient un array d'ids
  96.         $structures = [];
  97.         foreach ($ids as $id) {
  98.             $structure $this->getDoctrine()->getRepository(Structure::class)->find($id);
  99.             if($structure) {
  100.                 $key sprintf('%08d'$structure->getPriority()) . "_" substr($structure->getName(), 020) . "_" sprintf('%08d'$structure->getId()); // pour ksort par la suite
  101.                 if(! isset($structures[$key])) $structures[$key] = $structure;
  102.             }
  103.         }
  104.         krsort($structures);
  105.         return $this->render('structure/searchResult.html.twig', [
  106.             'listWithThumbnails' => $listWithThumbnails,
  107.             'structures' => $structures
  108.         ]);
  109.     }
  110.     
  111.     /**
  112.      * affiche la liste des structures non géolocalisées 
  113.      * @Route("/structures/non-geolocalisees", name="listNonGeolocalizedStructures")
  114.      */
  115.     public function listNonGeolocalizedStructures(Request $requestPaginatorInterface $paginator$pageLimit 30)
  116.     {
  117.         $title "Structures non-géolocalisées";
  118.         $structureRepository $this->getDoctrine()->getRepository(Structure::class);
  119.         // $structures = $structureRepository->findAllUnlocalized();
  120.         $pageNb $request->query->getInt('page'1);
  121.         $structures $paginator->paginate(
  122.             $structureRepository->getAllUnlocalizedQuery(), /* query NOT result */
  123.             $pageNb/*page number*/
  124.             $pageLimit /*limit per page*/
  125.         );
  126.             
  127.         return $this->render('structure/list.html.twig', [
  128.                 'structures' => $structures,
  129.                 'pageNb' => $pageNb,
  130.                 'pageLimit' => $pageLimit,
  131.                 'title' => $title
  132.         ]);
  133.     }
  134.     
  135.     /**
  136.      * affiche la liste des structures non géolocalisées 
  137.      * @Route("/structures/geolocalisees", name="listGeolocalizedStructures")
  138.      */
  139.     public function listGeolocalizedStructures(Request $requestPaginatorInterface $paginator$pageLimit 30)
  140.     {
  141.         $title "Structures géolocalisées";
  142.         $structureRepository $this->getDoctrine()->getRepository(Structure::class);
  143.         // $structures = $structureRepository->findAllLocalized();
  144.         $pageNb $request->query->getInt('page'1);
  145.         $structures $paginator->paginate(
  146.             $structureRepository->getAllLocalizedQuery(), /* query NOT result */
  147.             $pageNb/*page number*/
  148.             $pageLimit /*limit per page*/
  149.         );
  150.             
  151.         return $this->render('structure/list.html.twig', [
  152.                 'structures' => $structures,
  153.                 'pageNb' => $pageNb,
  154.                 'pageLimit' => $pageLimit,
  155.                 'title' => $title
  156.         ]);
  157.     }
  158.     
  159.     /**
  160.      * affiche la liste des structures par tag ou par theme 
  161.      * @Route("/structures-by-t/{type}/{slug}", name="listGeolocalizedStructuresByT", requirements={"type"="tag|theme"})
  162.      * @return JsonResponse avec la liste des infos necessaires par structure 
  163.      */
  164.     public function listGeolocalizedStructuresByT($type$slug null$limit 100)
  165.     {
  166.         $structureRepository $this->getDoctrine()->getRepository(Structure::class);
  167.         if(null == $slug) {
  168.             $structures $structureRepository->findAllLocalized($limit);
  169.         } else {
  170.             switch ($type) {
  171.                 case 'tag':
  172.                     $tagRepository $this->getDoctrine()->getRepository(Tag::class);
  173.                     $entity $tagRepository->findOneBySlug($slug);
  174.                 break;
  175.                 case 'theme':
  176.                     $themeRepository $this->getDoctrine()->getRepository(Theme::class);
  177.                     $entity $themeRepository->findOneBySlug($slug);
  178.                     break;
  179.             }
  180.             if(!$entity) throw $this->createNotFoundException('Pas de ' $type ' avec le slug "' $slug '".');
  181.     
  182.             $structures $structureRepository->findAllLocalizedByT($entity$limit);
  183.         }
  184.         $formattedStructures $this->_setFormattedStructuresForMap($structures);
  185.         
  186.         $response = new JsonResponse();
  187.         $response->setData([
  188.             'items' => $formattedStructures
  189.         ]);
  190.         
  191.         // dump($structures); dump($formattedStructures); dump($response); exit;
  192.         return $response;
  193.     }
  194.     
  195.     /**
  196.      * affiche la liste des structures par tag ou par theme 
  197.      * @Route("/structures-by-t/{id}", name="setGeolocalizedStructure", requirements={"id"="\d+"})
  198.      * @return JsonResponse avec la liste des infos necessaires pour la structure 
  199.      */
  200.     public function setGeolocalizedStructure($id)
  201.     {
  202.         $structureRepository $this->getDoctrine()->getRepository(Structure::class);
  203.         $structure $structureRepository->find($id);
  204.         if(!$structure) throw $this->createNotFoundException('Pas de structure avec l\'id "' $id '".');
  205.         $structures = [$structure];
  206.         if(! $structure->getLongitude() || ! $structure->getLatitude()) $structures = [];
  207.         $formattedStructures $this->_setFormattedStructuresForMap($structures);
  208.         
  209.         $response = new JsonResponse();
  210.         $response->setData([
  211.             'items' => $formattedStructures
  212.         ]);
  213.         
  214.         // dump($structures); dump($formattedStructures); dump($response); exit;
  215.         return $response;
  216.     }
  217.     
  218.     /**
  219.      * sous fonction pour formatter la réponse pour affichage sur carte de la liste des structures
  220.      * @return Array $formattedStructures avec la liste des infos necessaires pour la structure 
  221.      */
  222.     private function _setFormattedStructuresForMap($structures)
  223.     {
  224.         $formattedStructures = [];
  225.         foreach ($structures as $structure) {
  226.             if( $structure->getSlug() ) {
  227.                 $url $this->generateUrl('showStructureBySlug', ['slug' => $structure->getSlug()]);
  228.             } else {
  229.                 $url $this->generateUrl('showStructure', ['id' => $structure->getId()]);
  230.             }
  231.             if( $structure->getAddress() ) {
  232.                 $town $structure->getTown() ? " " $structure->getTown() : "";
  233.                 $postalCode $structure->getPostalCode() ? " " $structure->getPostalCode() : "";
  234.                 $descr $structure->getAddress() . $postalCode $town;
  235.             } else {
  236.                 $descr $structure->getName();
  237.             }
  238.             
  239.             $formattedStructure = [
  240.                 'long' => $structure->getLongitude(),
  241.                 'lat' => $structure->getLatitude(),
  242.                 'title' => $structure->getTitle(),
  243.                 'subtitle' => $structure->getSubtitle(),
  244.                 'name' => $structure->getName(),
  245.                 'descr' => $descr,
  246.                 'url' => $url
  247.             ];
  248.             $formattedStructures[] = $formattedStructure;
  249.         }
  250.         return $formattedStructures;
  251.     }
  252.     
  253.         
  254.     /**
  255.      * affiche la liste des structures partageant un tag avec la structure donnee 
  256.      * @Route("/same-structures/{id}/{limit}", name="listSame", requirements={"id"="\d+"})
  257.      * @return Structure[]  
  258.      */
  259.     public function listSame($id$limit 10)
  260.     {
  261.         $structureRepository $this->getDoctrine()->getRepository(Structure::class);
  262.         $structure $structureRepository->find($id);
  263.         
  264.         if(!$structure) throw $this->createNotFoundException('Pas de structure avec l\'id "' $id '".');
  265.         
  266.         $tags $structure->getTags();
  267.         $structures $structureRepository->findBySameTags($tags$limit$structure);
  268.         
  269.         $questionAnswerRepository $this->getDoctrine()->getRepository(QuestionAnswer::class);
  270.         $questionAnswers $questionAnswerRepository->findBySameTags($tags$limit);
  271.         // dump($structures); exit;
  272.         return $this->render('structure/listSame.html.twig', [
  273.             'structures' => $structures,
  274.             'questionAnswers' => $questionAnswers
  275.         ]);
  276.     }
  277. }