src/Dp/CalendarBundle/Controller/DefaultController.php line 96

Open in your IDE?
  1. <?php
  2. /*
  3.  * This file is part of the Symfocal Calendar v1.0.
  4.  *
  5.  * (c) Symfocal http://www.symfocal.com
  6.  * alban@symfocal.com
  7.  * 
  8.  * For the full copyright and license information, please view the LICENSE
  9.  * file that was distributed with this source code.
  10.  */
  11. namespace App\Dp\CalendarBundle\Controller;
  12. use App\Util\Util;
  13. use Doctrine\ORM\EntityManagerInterface;
  14. use App\Dp\CalendarBundle\Entity\Item;
  15. use App\Dp\CalendarBundle\Entity\State;
  16. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  17. use Symfony\Component\Routing\Annotation\Route;
  18. //use Symfony\Bundle\FrameworkBundle\Controller\Controller;
  19. use Symfony\Component\HttpFoundation\Response;
  20. use Symfony\Component\HttpFoundation\Request;
  21. use App\Dp\CalendarBundle\Entity\Booking;
  22. use Symfony\Component\HttpFoundation\Cookie;
  23. //use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
  24. use Symfony\Component\Security\Core\SecurityContext;
  25. use Symfony\Component\Translation\LocaleSwitcher;
  26. use Symfony\Contracts\Translation\TranslatorInterface;
  27. class DefaultController extends AbstractController
  28. {
  29.     private $em;
  30.     private $objUtil;
  31.     private $translator;
  32.     public function __construct(private LocaleSwitcher $localeSwitcherEntityManagerInterface $em,TranslatorInterface $translator)
  33.     {
  34.         $this->em $em;
  35.         $this->objUtil = new Util($this->em);
  36.         $this->translator $translator;
  37.     }
  38.     public function indexAction() 
  39.     {
  40.         return $this->render('DpCalendarBundle:Default:index.html.twig');
  41.     }
  42.     /**
  43.      * @return Response
  44.      */
  45.     public function indexAdminAction() 
  46.     {
  47.         //////////////////////////////////////
  48.         //all items followed with the calendar
  49.         //////////////////////////////////////
  50.         $items $this->em->getRepository(Item::class)->findBy(
  51.             array(),
  52.             array('position' => 'ASC'));
  53.         ////////////////////////////////////////
  54.         //first item on which calendar will open
  55.         ////////////////////////////////////////
  56.         $objItem =  $this->em->getRepository(Item::class)->findOneBy(
  57.             array(),
  58.             array('position' => 'ASC'), 11);
  59.         if (!$objItem)
  60.         {
  61.             $item null;
  62.         } else {
  63.             $item $objItem->getId();//first item on which calendar will open
  64.         }
  65.         ///////////////////////////////////
  66.         //all booking states for the legend
  67.         ///////////////////////////////////
  68.         $states $this->em->getRepository(State::class)->findBy(
  69.             array('item'        => $item),
  70.             array('position'    => 'ASC'));
  71.         return $this->render('Dp/CalendarBundle/Default/indexAdmin.html.twig', array(
  72.             'items'     => $items,
  73.             'item'      => $item,
  74.             'states'    => $states,
  75.             'util'      => $this->objUtil,
  76.             ));
  77.     }
  78.     /**
  79.      * $admin is a boolean parameter defined in routing.yml set at true for the admin page and false otherwise
  80.      *
  81.      * @param $admin
  82.      * @param $item
  83.      * @param Request $request
  84.      * @return Response
  85.      */
  86.     public function calendarDisplayAction($admin$itemRequest $request)
  87.     {
  88.         if ($item ==''$item = -1;
  89.         $date = new \DateTime();
  90.         $year $date->format('Y'); //to start calendar on current year
  91.         $month $date->format('m'); //to start calendar on current month
  92.         $day $date->format('d');
  93.         ///////////////////////////////////////
  94.         // all items followed with the calendar
  95.         /////////////////////////////////////////
  96.         $items $this->em->getRepository(Item::class)->findBy(
  97.             array(),
  98.             array('position' => 'ASC'));
  99.         
  100.         //$item =  $em->getRepository('DpCalendarBundle:Item')->findOneBy(array(), array('position' => 'ASC'), 1, 1)->getId();//first item on which calendar will open
  101.         if ($item == -1)
  102.         {
  103.             /////////////////////////////////////////
  104.             // first item on which calendar will open
  105.             /////////////////////////////////////////
  106.             $objItem =  $this->em->getRepository(Item::class)->findOneBy(
  107.                 array(),
  108.                 array('position' => 'ASC'), 11);
  109.             if (!$objItem)
  110.             {
  111.                 $item null;
  112.             } else {
  113.                 $item $objItem->getId();//first item on which calendar will open
  114.             }
  115.         }
  116.         
  117.         $states $this->em->getRepository(State::class)->findBy(
  118.             array('item'        => $item),
  119.             array('position'    => 'ASC'));//all booking states for the legend
  120.         //$statesLellenda = $em->getRepository('DpCalendarBundle:State')->findBy(array(), array('position' => 'ASC'));//all booking states for the legend
  121.         if ($admin)
  122.         {
  123.             $er $this->em->getRepository(State::class);
  124.             $qb $er->createQueryBuilder('a');
  125.             $qb->groupBy('a.class')
  126.                     ->add('orderBy'"a.position ASC");
  127.             $statesLellenda $qb->getQuery()->getResult();
  128.         } else {
  129.             $statesLellenda $states;
  130.         }
  131.         return $this->render('Dp\CalendarBundle\Default\calendar.html.twig', array(
  132.             'year'              => $year,
  133.             'month'             => $month,
  134.             'day'               => $day,
  135.             'admin'             => $admin,
  136.             'items'             => $items,
  137.             'item'              => $item,
  138.             'states'            => $states,
  139.             'statesLellenda'    => $statesLellenda,
  140.             'locale'            => $request->getLocale()
  141.         ));
  142.     }
  143.     /**
  144.      * controller called via ajax to fill calendar for a specific month, year and item
  145.      * @return Response
  146.      */
  147.     public function calendarAction(Request $request)
  148.     {        
  149.         $oneday = new \DateInterval('P1D');
  150.         
  151.         $states =  $this->em->getRepository(State::class)->findBy(
  152.             array(),
  153.             array("position" => 'ASC'), 10);
  154.         $defaultClass '';
  155.         foreach($states as $state)
  156.         {
  157.             $defaultClass=$state->getClass();
  158.         }
  159.         
  160.         //$request = $this->get('request');
  161.         $yearKey=intval($request->request->get('year'));
  162.         $monthKey=intval($request->request->get('month'));
  163.         $itemId=intval($request->request->get('itemId'));
  164.         if ($monthKey==0$monthKey=12;
  165.         
  166.         $item $this->em->getRepository(Item::class)->find($itemId);
  167.         if (!$item)
  168.         {
  169.             $return='{"responseCode" : "400", "message" : "the item selected does not exist - please restart the application"}';// if  the item is not found, an ajax response is sent with a message to be displayed
  170.             return new Response($return,200,array('Content-Type'=>'application/json'));
  171.         }
  172.         
  173.         $lowLimit = new \DateTime();//low limit date used to select dates in the booking table
  174.         $highLimit = new \DateTime();//high limit date used to select dates in the booking table
  175.         $lowLimit->setDate($yearKey$monthKey1);
  176.         $lowLimit->sub($oneday);
  177.         $highLimit->setDate($yearKey$monthKey31);
  178.         $highLimit->add($oneday);
  179.         
  180.         $er $this->em->getRepository(Booking::class);
  181.         $qb $er->createQueryBuilder('a');
  182.         $qb->where('a.theDate BETWEEN :lowLimit AND :highLimit')
  183.                 ->setParameter('lowLimit'$lowLimit)
  184.                 ->setParameter('highLimit'$highLimit)
  185.                 ->andWhere('a.item = :item')
  186.                 ->setParameter('item'$item);
  187.         $entities $qb->getQuery()->getResult();
  188.         $bookings = array();
  189.         foreach ($entities as $booking)
  190.         {
  191.             $key $booking->getTheDate()->format('Y-m-d');
  192.             //$bookings[$key]=$booking->getState()->getClass();//for each date found in the query, class to be applied is stored in array $bookings()            
  193.             $objBookings $booking->getState();
  194.             $sClass '';
  195.             if ($objBookings)
  196.             {
  197.                 $sClass $objBookings->getClass();//for each date found in the query, class to be applied is stored in array $bookings()
  198.             }
  199.             $bookings[$key] = $sClass;//for each date found in the query, class to be applied is stored in array $bookings()
  200.         }
  201.         
  202.         $return='';
  203.         $current_month $this->getMonth($monthKey);
  204.         $title htmlentities($current_month." ".$yearKey ,ENT_QUOTES);
  205.         $return.='"current_month" : "'.$title.'" , ';
  206.         $previous_month=$this->getOtherMonth($monthKey,$yearKey,-1);//needed to calculate the number of days of previous month
  207.         $days_previous_month date('t',mktime(000$previous_month[$monthKey], 1$previous_month[$yearKey])); //number of days of the previous month, used to populate the calendar cells corresponding to the previous month.
  208.         $return.='"days_previous_month" : "'.$days_previous_month.'" , ';
  209.       
  210.         //The following 4 arrays will contain all the information for each cell of the calendar table.
  211.         $tab_days = array();
  212.         $tab_booked = array();
  213.         $tab_class = array();
  214.         $tab_dates = array();
  215.    
  216.         $num_day $this->getFirstDay($monthKey,$yearKey);
  217.         $count 1;
  218.         $num_day_current 1;
  219.         $nb_days_prev 0;
  220.         
  221.         while ($count<43)
  222.         {
  223.             if ($count<$num_day)
  224.             {
  225.                 $nb_days_prev++;//counts the number of days of previous month appearing on a calendar.
  226.                 $tab_days[$count]=0;
  227.                 $tab_booked[$count]=-1;
  228.                 $tab_class[$count]="";//only actual days of the targeted month will have their class stored here
  229.                 $tab_dates[$count]="";//only actual days of the targeted month will have their date stored here
  230.             } else {
  231.                 if (checkdate($monthKey,$num_day_current,$yearKey))//if the date is valid
  232.                 {
  233.                     $datetime = new \DateTime();
  234.                     $date=$datetime->setDate($yearKey$monthKey$num_day_current)->format('Y-m-d');
  235.                     $tab_dates[$count]=$date;
  236.                     if (array_key_exists($date$bookings))//if the date has been found in the booking table for the targeted item
  237.                     {
  238.                         $tab_days[$count]=$num_day_current;
  239.                         $tab_booked[$count]=1;
  240.                         $tab_class[$count]=$bookings[$date];
  241.                     } else {
  242.                         $tab_days[$count]=$num_day_current;
  243.                         $tab_booked[$count]=0;
  244.                         $tab_class[$count]=$defaultClass;//if the date has not been found in the booking table for the targeted item, then we apply the class of the first state
  245.                     }
  246.                     $num_day_current++;
  247.                 } else {
  248.                     $tab_days[$count]=$count-$num_day_current-$nb_days_prev+1;//used to display the days of the next month displayed on the calendar
  249.                     $tab_booked[$count]=-2;
  250.                     $tab_class[$count]="";
  251.                     $tab_dates[$count]="";
  252.                 }
  253.             }
  254.             $count++;
  255.         }
  256.         
  257.         $return.='"nb_days_prev" : "'.$nb_days_prev.'" , ';
  258.         
  259.         //now starts the actual building of the JSON response
  260.         if (!empty($tab_days))
  261.         {
  262.             $return.=' "calendar" : [ ';
  263.             $count 1;
  264.             while ($count 43)
  265.             {
  266.                 if ($count == 42)
  267.                 {
  268.                     $return.=' { "fill" : "'.$tab_days[$count].'", "booked" : "'.$tab_booked[$count].'", "classe" : "'.$tab_class[$count].'", "dates" : "'.$tab_dates[$count].'" } ';
  269.                 } else {
  270.                     $return.=' { "fill" : "'.$tab_days[$count].'", "booked" : "'.$tab_booked[$count].'", "classe" : "'.$tab_class[$count].'", "dates" : "'.$tab_dates[$count].'" } , ';
  271.                 }
  272.             $count++;
  273.             }
  274.             $return.=' ] ';
  275.         }
  276.         $return.=' } ';
  277.         $return='{"responseCode" : "200", '.$return;
  278.         return new Response($return,200,array('Content-Type'=>'application/json'));//make sure it has the correct content type
  279.     }
  280.     /**
  281.      * controller called via ajax when a date is clicked on administration panel
  282.      * @return Response
  283.      * @throws \Doctrine\ORM\NonUniqueResultException
  284.      */
  285.     public function ajaxAdminAction(Request $request)
  286.     {        
  287.         //$request = $this->get('request');
  288.         $date=$request->request->get('date');
  289.         $id=$request->request->get('id');
  290.         $itemId=$request->request->get('itemId');
  291.         $clickMethod=$request->request->get('clickMethod');
  292.         
  293.         $item $this->em->getRepository(Item::class)->find($itemId);
  294.         if (!$item)
  295.         {
  296.             $return='{"responseCode" : "400", "message" : "the item selected does not exist - please restart the application"}';// if  the item is not found, an ajax response is sent with a message to be displayed
  297.             return new Response($return,200,array('Content-Type'=>'application/json'));
  298.         }
  299.         
  300.         if ($clickMethod>0)
  301.         {
  302.             $stateSelected $this->em->getRepository(State::class)->find($clickMethod);
  303.             if (!$stateSelected)
  304.             {
  305.                 $return='{"responseCode" : "400", "message" : "the state selected does not exist - please restart the application"}';// if  the state selected is not found, an ajax response is sent with a message to be displayed
  306.                 return new Response($return,200,array('Content-Type'=>'application/json'));
  307.             }
  308.         }
  309.         
  310.         $yearKey substr($date04);
  311.         $monthKey substr($date52);
  312.         $dayKey substr($date82);
  313.         $target = new \DateTime();
  314.         $target->setDate($yearKey$monthKey$dayKey);
  315.         $target->setTime(000);//necessary to be able to test equality between dates in the following query
  316.          
  317.         $er $this->em->getRepository(Booking::class);
  318.         $qb $er->createQueryBuilder('a');
  319.         $qb->where('a.theDate = :theDate')
  320.             ->setParameter('theDate'$target)
  321.             ->andWhere('a.item = :item')
  322.             ->setParameter('item'$item);
  323.         $entity $qb->getQuery()->getOneOrNullResult();
  324.         
  325.         $return='';
  326.         
  327.         $return.='"id_returned" : "'.$id.'" , ';
  328.         $return.='"date_returned" : "'.$date.'" , ';
  329.         /////////////////////////////////////////////////////////////////////////////////////////
  330.         //if the date is not found in the booking table for the targeted item, then it is created
  331.         /////////////////////////////////////////////////////////////////////////////////////////
  332.         if ($entity==null)
  333.         {
  334.             if ($clickMethod != 0)
  335.             {
  336.                 $booking = new Booking();
  337.                 $booking->setTheDate($target);
  338.                 $booking->setItem($item);
  339.                 $booking->setState($stateSelected);
  340.                 $this->em->persist($booking);
  341.                 $this->em->flush();
  342.                 $return.='"state" : "'.$booking->getState()->getClass();
  343.             } else {
  344.                 $return.='"state" : "';
  345.             }
  346.         } else {
  347.             ////////////////////////////////////////////////////////////////////////////
  348.             // click through method is selected, meaning the new state is the next state
  349.             ///////////////////////////////////////////////////////////////////////////
  350.             if ($clickMethod == 0)
  351.             {
  352.                 $this->em->remove($entity);
  353.                 $this->em->flush();
  354.                 $return.='"state" : "';
  355.             } else {
  356.                 $entity->setState($stateSelected);
  357.                 $this->em->persist($entity);
  358.                 $this->em->flush();
  359.                 $return.='"state" : "'.$entity->getState()->getClass();
  360.             }
  361.         }
  362.         $return='{"responseCode" : "200", '.$return.'" }';
  363.         return new Response($return,200,array('Content-Type'=>'application/json'));//make sure it has the correct content type
  364.     }
  365.     /**
  366.      * controller called via ajax when a date is clicked on administration panel
  367.      *
  368.      * @return Response
  369.      */
  370.     public function ajaxChangeStateAction(Request $request)
  371.     {
  372.         $return='';
  373.         //$request = $this->get('request');
  374.         $itemId $request->request->get('itemId');
  375.         // Si fem la crida per fer proves per get
  376.         if ($itemId == ''$itemId $request->query->get('itemId');
  377.         $objState $this->em->getRepository(State::class)->findBy(
  378.             array('item' => $itemId),
  379.             array('position' => 'ASC')
  380.         );
  381.         if (!$objState)
  382.         {
  383.             $return='{"responseCode" : "400", "message" : "the state selected does not exist - please restart the application"}';// if  the state selected is not found, an ajax response is sent with a message to be displayed
  384.             return new Response($return,200,array('Content-Type'=>'application/json'));
  385.         } else {
  386.             $return.='"state" : [  '
  387.             foreach ($objState as $states)
  388.             {
  389.                 //echo $states->getName();
  390.                 //echo '<pre>';
  391.                 //print_r($states);
  392.                 //echo '</pre>';
  393.                 
  394.                 if ($return != '"state" : [  '$return.=',';
  395.                 $return.='{"id_returned" : "' $states->getid() . '" , ';
  396.                 $return.='"name_returned" : "' $states->getName() . '" , ';
  397.                 $return.='"class_returned" : "' $states->getclass() . '" }';
  398.             }
  399.             $return.=']'
  400.         }
  401.         $return='{"responseCode" : "200", ' $return ' }';
  402.         return new Response($return,200,array('Content-Type'=>'application/json'));//make sure it has the correct content type
  403.     }
  404.     
  405.     /**
  406.      * Function returning the name of the month based on its number - accents are javascript encoded
  407.      *
  408.      * @param $monthKey
  409.      * @return mixed
  410.      */
  411.     function getMonth($monthKey)
  412.     {
  413.         $monthKey=sprintf("%d",$monthKey);
  414.         $tab_mois=array(    1   =>  $this->translator->trans("Gener"),
  415.                                     $this->translator->trans("Febrer"),
  416.                                     $this->translator->trans("Març"),
  417.                                     $this->translator->trans("Abril"),
  418.                                     $this->translator->trans("Maig"),
  419.                                     $this->translator->trans("Juny"),
  420.                                     $this->translator->trans("Juliol"),
  421.                                     $this->translator->trans("Agost"),
  422.                                     $this->translator->trans("Setembre"),
  423.                                     $this->translator->trans("Octubre"),
  424.                                     $this->translator->trans("Novembre"),
  425.                                     $this->translator->trans("Desembre"));
  426.         return $tab_mois[$monthKey];
  427.     }
  428.      
  429.     //Function returning following or previous month and year based on $pas
  430.     function getOtherMonth($monthKey,$yearKey,$pas)
  431.     {
  432.         $tmstp_suivant=mktime(0,0,0,($monthKey+$pas),1,$yearKey);
  433.         $date_suivante[$monthKey]=date("m",$tmstp_suivant);
  434.         $date_suivante[$yearKey]=date("Y",$tmstp_suivant);
  435.         return $date_suivante;
  436.     }
  437.      
  438.     //Function returning the first day of the month
  439.     function getFirstDay($monthKey,$yearKey)
  440.     {
  441.         $tmstp=mktime(0,0,0,$monthKey,1,$yearKey);
  442.         $dayKey=date("w",$tmstp);
  443.         
  444.         $tab_jour=array(0=>7,1=>1,2=>2,3=>3,4=>4,5=>5,6=>6);//This is for calendars with weeks starting on Mondays. Sunday returns a 0 which must be changed to 7
  445.         
  446.         return $tab_jour[$dayKey];//for calendars with weeks starting on Sundays, just return $dayKey.
  447.     }
  448. }