src/Controller/HomeController.php line 59

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. use App\Entity\{CategoryDepartment};
  4. use Doctrine\Persistence\ManagerRegistry;
  5. use Symfony\Component\HttpFoundation\Request;
  6. use Symfony\Component\HttpFoundation\Response;
  7. use Symfony\Component\Routing\Annotation\Route;
  8. use App\Service\{CardsServiceDepartmentServiceSpecialCharService};
  9. class HomeController extends CoreController
  10. {   
  11.     /**
  12.     * @Route("/", name="app_home")
  13.     */
  14.     public function display(SpecialCharService $specialCharServiceCardsService $cards): Response
  15.     {
  16.         // We get back the session to see if the user is logged in 
  17.         // And to check if they have clearance to see the homepage
  18.         $session $this->requestStack->getSession();
  19.         $session->remove('sector');
  20.         $session->remove('service');
  21.         
  22.         $response $this->getAuthorizationResponse($session);
  23.         if ($response instanceof Response) {
  24.             return $this->render('errors.html.twig'$session->get('error'), $response);
  25.         }
  26.         // Defining the titles of the homepage
  27.         extract($cards->getTitles($specialCharService0));
  28.         // We create an associative array of the departments in order to get only the properties we need
  29.         $departmentsArray $cards->setDepartmentsArray($specialCharService);
  30.         
  31.         $departmentsArray $cards->addImagesOnDepartments($departmentsArray);
  32.         dump($departmentsArray);
  33.         // TODO : delete line when DEVE okay
  34.         array_pop($departmentsArray);
  35.         // dump($departmentsArray);
  36.         
  37.         return $this->render('home.html.twig', [
  38.             'categories' => $departmentsArray,
  39.             "sector" => $sector,
  40.             "service" => $serviceArray,
  41.             "headerLink" => 'app_home'
  42.             "department" => 0
  43.         ]);
  44.     }
  45.     /**
  46.     * @Route("/deve", name="app_department_5")
  47.     * @Route("/snap", name="app_department_4")
  48.     * @Route("/service-de-la-documentation", name="app_department_3")
  49.     * @Route("/direction-des-affaires-financieres-et-comptables", name="app_department_2")
  50.     * @Route("/direction-du-patrimoine", name="app_department_1")
  51.     */
  52.     public function displayDepartment(Request $requestSpecialCharService $specialCharServiceCardsService $cards)
  53.     {
  54.         
  55.         $currentPath substr($request->getPathInfo(), 1); // the URI path being requested
  56.         $id $cards->getDepartmentId($currentPath);
  57.         $session $this->requestStack->getSession();
  58.         
  59.         $response $this->getAuthorizationResponse($session);
  60.         if ($response instanceof Response) {
  61.             return $this->render('errors.html.twig'$session->get('error'), $response);
  62.         }
  63.         extract($cards->getTitles($specialCharService$id));
  64.         // We create an associative array of the departments in order to get only the properties we need
  65.         $departmentsArray $cards->setDepartmentsArray($specialCharService$id);
  66.         // Sets the categories into the $departmentsArray, with their properties, image and route.
  67.         $cardsArray $cards->setCategories($departmentsArray$id);
  68.         return $this->render('patrimoine/home.html.twig', [
  69.             'categories' => $cardsArray,
  70.             "sector" => $sector,
  71.             "service" => $serviceArray,
  72.             "id" => $id,
  73.             "headerLink" => 'app_home'
  74.         ]);
  75.     }
  76.     /**
  77.     * @Route("/deve/ticket/success", name="app_success_5")
  78.     * @Route("/snap/ticket/success", name="app_success_4")
  79.     * @Route("/service-de-la-documentation/ticket/succes", name="app_success_3")
  80.     * @Route("/direction-des-affaires-financieres-et-comptables/ticket/succes", name="app_success__2")
  81.     * @Route("/direction-du-patrimoine/ticket/succes", name="app_success__1")
  82.     */
  83.     public function showSuccess(): Response
  84.     {
  85.         $session $this->requestStack->getSession();
  86.         $ticketId $session->get('ticketId');
  87.        
  88.         extract($this->handleUrlParams($session));
  89.         $messages = ["Votre demande a été envoyée avec succès."];
  90.         
  91.         if ($sector === '3') {
  92.             $target "le site de l'Université";
  93.             $messages = [...$messages"Elle sera traitée sous 72 heures ouvrées."];
  94.         }
  95.         else {
  96.             $target "la page d'Accueil";
  97.         }
  98.         
  99.         return $this->render('form-success.html.twig', [
  100.             'messages' => $messages,
  101.             'sector' => $department,
  102.             'sectorId' => $sector,
  103.             'service' => $service,
  104.             'ticketId' => $ticketId,
  105.             'target' => $target,
  106.             "headerLink" => 'app_department_' $sector
  107.         ]);
  108.     }
  109.     /**
  110.      * Transforms the $departments array of objects into an array of associative arrays
  111.      * And filters the data so as to keep the only needed properties 
  112.      *
  113.      * @param array $departments
  114.      * @return array
  115.      */
  116.     private function setDepartmentsArray(ManagerRegistry $doctrineSpecialCharService $specialCharService) {
  117.         $departments $doctrine->getRepository(Department::class)->findAll();
  118.         
  119.         $newDepartmentArray = [];
  120.         foreach ($departments as $currentDepartment) { 
  121.             $newDep = [];
  122.             $newDep['id'] = $currentDepartment->getId();
  123.             $newDep['label'] = $currentDepartment->getXlab();
  124.             // $newDep['label'] = $specialCharService->setHomeCardsSpecialChars($currentDepartment);
  125.             $newDep['visibility'] = $currentDepartment->getVisi();
  126.             $newDep['categories'] = [];
  127.             array_push($newDepartmentArray$newDep);
  128.         }
  129.         return $newDepartmentArray;
  130.     }
  131.     /**
  132.      * Method that gathers many functions to create the array that will receives all categories, sorted by department, with the needed properties, route and image.
  133.      *
  134.      * @param ManagerRegistry $doctrine
  135.      * @param array $departments
  136.      * @return array
  137.      */
  138.     private function setCategories(ManagerRegistry $doctrine$departments$service) {
  139.         
  140.         // We get all the categories from the database
  141.         $categories $doctrine->getRepository(Category::class)->findAll();
  142.         // Adds the property route to each $categories, whether they do or don't have a matching route
  143.         // route can be an empty array or an array containing the route name and the department and category IDs
  144.         $categoriesWihRoutes $this->setRoutesOnAllCategories($categories);
  145.         // Now we fetch the parent categories
  146.         $parents array_filter($categoriesWihRoutes, function($cat) {
  147.             return $cat->getParentId() === null;
  148.         });
  149.         // And them we assign them their children and grand-children
  150.         $children $service->setChildren($parents$categoriesWihRoutes$doctrine);
  151.         // Now we put all the matching categories into their parent array
  152.         $sortedArray $this->sortByDepartmentAndAddImage($children$departments);
  153.         // And finally, we replace empty sub-categories with they parent category.
  154.         $finalCardsArray $this->replaceEmptySubCategories($sortedArray);
  155.         $finalCardsArray $this->setOrderFirstDepartment($finalCardsArray);
  156.         
  157.         return $finalCardsArray;
  158.     }
  159.     /**
  160.      * To each category, the functions adds a route if there is a match.
  161.      * It also sets the the rigth title/name for the category
  162.      *
  163.      * @param array $categories
  164.      * @return array
  165.      */
  166.     private function setRoutesOnAllCategories($categories) {
  167.         
  168.         $newCardsArray array_map(function($cat) {
  169.             require __DIR__ '/../Data/cardsData.php';
  170.             
  171.             // Retrieves the keys of the array
  172.             $arrayKeys array_keys($routes);
  173.                         
  174.             // To each category, we assgin an empty array as default route name
  175.             $cat->setRouteName([]);
  176.             // We change the label of the category so as to the client can read the special characters
  177.             $cat->setXlab(SpecialCharService::setHomeCardsSpecialChars($cat));
  178.             // Now we check the $arrayKeys
  179.             foreach ($arrayKeys as $key) {
  180.                 // If the current key is contained in the category label
  181.                 if (str_contains(strtolower($cat->getXlab()), $key)) {
  182.                     // We set the matching route with the value associated to the key
  183.                     
  184.                     // TODO : find a solution to keep the 34th category to ignore the reprographie route because of the "format" part of the name
  185.                     if ($cat->getId() !== '34') {
  186.                         
  187.                       $cat->setRouteName($routes[$key]);
  188.                     }
  189.                     
  190.                 }
  191.             }            
  192.             return $cat;
  193.         }, $categories);
  194.         
  195.         return $newCardsArray;
  196.     }
  197.     
  198.     /**
  199.      * Complex function that identifies a category's children and stores into a sub-category roperty all of its children/grand-children 
  200.      *
  201.      * @param array $parents
  202.      * @param array $children array of categories with routes 
  203.      * @return array
  204.      */
  205.     private function setChildren($parents$categoriesManagerRegistry $doctrine) {
  206.         // DISCLAIMER : we are dealing with three different levels of categories, all stored in the same table of the database.
  207.         // Some of the categories are actually more like ticket subjects, we need to identify them
  208.         $subjectsIds = ['34''35''36'];
  209.         // For each parent category, we need to find if there are any children
  210.         foreach ($parents as $parent) {
  211.             // We create a new property, an array, that will welcome all of the sub-categories 
  212.            $parent->subCategories =  [];
  213.            // And a new array to welcome the current parent's children
  214.            $children = [];
  215.            // For each category
  216.            foreach($categories as $category) {
  217.                 // If the current $category has a parentId property that matches the current $parent id
  218.                 if ($category->getParentId() === $parent->getId()) {
  219.                     // We push the category into the children array.
  220.                     array_push($children$category);
  221.                 }
  222.            }
  223.            
  224.            // if there is a least one child, meaning the current category's parentId matches the current parent id
  225.            if (count($children) > 0) {
  226.                 foreach($children as $child) {
  227.                     // We now check if there are any grandchildren to the current child
  228.                     $grandChildren $doctrine->getRepository(Category::class)->findByParentId($child->getId());
  229.                     // If the current child id is in the $subjectsIds
  230.                     if (array_search($child->getId(), $subjectsIds) !== false) {
  231.                         // We retrieve its index so as to unset it
  232.                         $childIndex array_search($child$children);
  233.                         unset($children[$childIndex]);
  234.                     }
  235.                     // Then we push the grandchildren into the children array
  236.                     // That way, we put them at the same level
  237.                     foreach ($grandChildren as $grandChild) {
  238.                         array_push($children$grandChild) ;
  239.                     }
  240.                     
  241.                     // Finally, if there are any grandchildren
  242.                     if (count($grandChildren) > 0) {
  243.                         // We retrieve the index of the child in the children array so as to delete it
  244.                         // Meaning the grandchildren actually replace the child
  245.                         $childIndex array_search($child$children);
  246.                         unset($children[$childIndex]);
  247.                     }
  248.                 };
  249.             // Finally, we push the children into the subCategories array we created at the beginning
  250.             array_push($parent->subCategories,...$children) ;
  251.            }
  252.         }
  253.         return $parents;
  254.     }
  255.     /**
  256.      * Stores the parent categories into the departments array
  257.      * In the process, adds the image matching the department
  258.      *
  259.      * @param array $categories
  260.      * @param array $departments
  261.      * @return array
  262.      */
  263.     private function sortByDepartmentAndAddImage($categories$departments) {
  264.         include __DIR__ '/../Data/cardsData.php';
  265.         // Retrieves the keys of the array
  266.         $imagesArrayKeys array_keys($images);
  267.         $newDepArray = [];
  268.         foreach ($departments as $department) {
  269.             foreach ($categories as $category) {
  270.                 // if the current category's departmentId matches the current department's id
  271.                 if ($category->getDepaId() === $department['id']) {                    
  272.                     // We push the category into the categories property of the department
  273.                     array_push($department['categories'], $category);
  274.                 }
  275.             }
  276.             
  277.             foreach ($imagesArrayKeys as $imageKey) {
  278.                 // If the department's label contains the image key
  279.                 if (str_contains($department['label'], $imageKey)) {
  280.                     // We add the image property to the department
  281.                     $department['image'] = $images[$imageKey];
  282.                 }
  283.             }
  284.             array_push($newDepArray$department);
  285.         }
  286.         return $newDepArray;
  287.     }
  288.     /**
  289.      * Functions that checks if the sub-categories array is empty      
  290.      *
  291.      * @param array $cards
  292.      * @return array
  293.      */
  294.     private function replaceEmptySubCategories ($cards) {
  295.         $newCardsArray array_map(function($card) { // department level
  296.             $categories array_map(function($cat) { // categories level
  297.                 // If there are no subcategories
  298.                 if (count($cat->subCategories) === 0) {
  299.                     // We create a clone of the current category and we set it as the subcategory
  300.                     $clone = clone $cat;
  301.                     $cat->subCategories = [$clone];
  302.                 }
  303.                 return $cat;
  304.             }, $card['categories']);
  305.             $card['categories'] = $categories;
  306.             return $card;
  307.         }, $cards);
  308.         
  309.         return $newCardsArray;
  310.     }
  311.     /**
  312.      * Rearranges the sub-categories of the Logistique category
  313.      * Descending order based on name length 
  314.      *
  315.      * @param array $cards
  316.      * @return array
  317.      */
  318.     private function setOrderFirstDepartment ($cards) {
  319.         $orderedSubcategories = [];
  320.         foreach ($cards[0]['categories'][0]->subCategories as $category) {
  321.             $orderedSubcategories[strlen($category->getXlab())] = $category;
  322.         }
  323.         // Sorts the array by key, in ascending order
  324.         ksort($orderedSubcategories);
  325.         $cards[0]['categories'][0]->subCategories $orderedSubcategories;
  326.         return $cards;
  327.     }
  328. }