]> Raphaƫl G. Git Repositories - airbundle/blobdiff - Controller/LocationController.php
Update facebook image
[airbundle] / Controller / LocationController.php
index ad28644f0878fe6295c96706b850d3c347acbc92..0cb09f35f8995e5a55a47c9d5d54672127d24659 100644 (file)
 namespace Rapsys\AirBundle\Controller;
 
 use Symfony\Component\HttpFoundation\Request;
 namespace Rapsys\AirBundle\Controller;
 
 use Symfony\Component\HttpFoundation\Request;
+use Symfony\Component\HttpFoundation\Response;
+use Symfony\Component\Routing\RequestContext;
+use Symfony\Component\Routing\Exception\MethodNotAllowedException;
+use Symfony\Component\Routing\Exception\ResourceNotFoundException;
 use Rapsys\AirBundle\Entity\Slot;
 use Rapsys\AirBundle\Entity\Slot;
+use Rapsys\AirBundle\Entity\Session;
+use Rapsys\AirBundle\Entity\Location;
 
 class LocationController extends DefaultController {
        /**
 
 class LocationController extends DefaultController {
        /**
-        * List all locations
+        * Add location
         *
         *
-        * @desc Display all sessions by location with an application or login form
+        * @desc Persist location in database
         *
         * @param Request $request The request instance
         *
         *
         * @param Request $request The request instance
         *
-        * @return Response The rendered view
+        * @return Response The rendered view or redirection
+        *
+        * @throws \RuntimeException When user has not at least admin role
         */
         */
-       public function index(Request $request = null) {
-               //Set section
-               $section = $this->translator->trans('Locations');
+       public function add(Request $request) {
+               //Prevent non-guest to access here
+               $this->denyAccessUnlessGranted('ROLE_ADMIN', null, $this->translator->trans('Unable to access this page without role %role%!', ['%role%' => $this->translator->trans('Admin')]));
+
+               //Create LocationType form
+               $form = $this->createForm('Rapsys\AirBundle\Form\LocationType', null, [
+                       //Set the action
+                       'action' => $this->generateUrl('rapsys_air_location_add'),
+                       //Set the form attribute
+                       'attr' => []
+               ]);
 
 
-               //Set title
-               $title = $section.' - '.$this->translator->trans($this->config['site']['title']);
+               //Refill the fields in case of invalid form
+               $form->handleRequest($request);
 
 
-               //Init context
-               $context = [];
+               //Handle invalid form
+               if (!$form->isSubmitted() || !$form->isValid()) {
+                       //Set section
+                       $section = $this->translator->trans('Location add');
 
 
-               //Create application form for role_guest
-               if ($this->isGranted('ROLE_GUEST')) {
-                       //Create ApplicationType form
-                       $application = $this->createForm('Rapsys\AirBundle\Form\ApplicationType', null, [
-                               //Set the action
-                               'action' => $this->generateUrl('rapsys_air_application_add'),
-                               //Set the form attribute
-                               'attr' => [ 'class' => 'col' ],
-                               //Set admin
-                               'admin' => $this->isGranted('ROLE_ADMIN'),
-                               //Set default user to current
-                               'user' => $this->getUser()->getId(),
-                               //Set default slot to evening
-                               //XXX: default to Evening (3)
-                               'slot' => $this->getDoctrine()->getRepository(Slot::class)->findOneById(3),
-                               //Set shorted return url
-                               'return' => $this->slugger->short(json_encode(['_route' => $request->get('_route'), '_route_params' => $request->get('_route_params')]))
-                       ]);
+                       //Set title
+                       $title = $this->translator->trans($this->config['site']['title']).' - '.$section;
 
 
-                       //Add form to context
-                       $context['application'] = $application->createView();
-               //Create login form for anonymous
-               } elseif (!$this->isGranted('IS_AUTHENTICATED_REMEMBERED')) {
-                       //Create ApplicationType form
-                       $login = $this->createForm('Rapsys\UserBundle\Form\LoginType', null, [
-                               //Set the action
-                               'action' => $this->generateUrl('rapsys_user_login'),
-                               //Set the form attribute
-                               'attr' => [ 'class' => 'col' ]
-                       ]);
-
-                       //Add form to context
-                       $context['login'] = $login->createView();
+                       //Render the view
+                       return $this->render('@RapsysAir/location/add.html.twig', ['title' => $title, 'section' => $section, 'form' => $form->createView()]+$this->context);
                }
 
                }
 
-               $calendar = 'toto';
+               //Get doctrine
+               $doctrine = $this->getDoctrine();
+
+               //Get manager
+               $manager = $doctrine->getManager();
 
 
-               //Render the view
-               return $this->render('@RapsysAir/location/index.html.twig', ['title' => $title, 'section' => $section, 'calendar' => $calendar]+$context+$this->context);
-       }
+               //Get location
+               $location = $form->getData();
+
+               //Set created
+               $location->setCreated(new \DateTime('now'));
+
+               //Set updated
+               $location->setUpdated(new \DateTime('now'));
+
+               //Queue location save
+               $manager->persist($location);
+
+               //Flush to get the ids
+               $manager->flush();
+
+               //Add notice
+               $this->addFlash('notice', $this->translator->trans('Location %id% created', ['%id%' => $location->getId()]));
+
+               //Extract and process referer
+               if ($referer = $request->headers->get('referer')) {
+                       //Create referer request instance
+                       $req = Request::create($referer);
+
+                       //Get referer path
+                       $path = $req->getPathInfo();
 
 
-       public function show(Request $request, $id) {
+                       //Get referer query string
+                       $query = $req->getQueryString();
+
+                       //Remove script name
+                       $path = str_replace($request->getScriptName(), '', $path);
+
+                       //Try with referer path
+                       try {
+                               //Save old context
+                               $oldContext = $this->router->getContext();
+
+                               //Force clean context
+                               //XXX: prevent MethodNotAllowedException because current context method is POST in onevendor/symfony/routing/Matcher/Dumper/CompiledUrlMatcherTrait.php+42
+                               $this->router->setContext(new RequestContext());
+
+                               //Retrieve route matching path
+                               $route = $this->router->match($path);
+
+                               //Reset context
+                               $this->router->setContext($oldContext);
+
+                               //Clear old context
+                               unset($oldContext);
+
+                               //Extract name
+                               $name = $route['_route'];
+
+                               //Remove route and controller from route defaults
+                               unset($route['_route'], $route['_controller']);
+
+                               //Check if location view route
+                               if ($name == 'rapsys_air_location_view' && !empty($route['id'])) {
+                                       //Replace id
+                                       $route['id'] = $location->getId();
+                               //Other routes
+                               } else {
+                                       //Set location
+                                       $route['location'] = $location->getId();
+                               }
+
+                               //Generate url
+                               return $this->redirectToRoute($name, $route);
+                       //No route matched
+                       } catch(MethodNotAllowedException|ResourceNotFoundException $e) {
+                               //Unset referer to fallback to default route
+                               unset($referer);
+                       }
+               }
+
+               //Redirect to cleanup the form
+               return $this->redirectToRoute('rapsys_air', ['location' => $location->getId()]);
        }
 
        }
 
-       public function toto(Request $request) {
+       /**
+        * Edit location
+        *
+        * @desc Persist location in database
+        *
+        * @param Request $request The request instance
+        *
+        * @return Response The rendered view or redirection
+        *
+        * @throws \RuntimeException When user has not at least guest role
+        */
+       public function edit(Request $request, $id) {
                //Prevent non-admin to access here
                //Prevent non-admin to access here
-               $this->denyAccessUnlessGranted('ROLE_GUEST', null, 'Unable to access this page without ROLE_GUEST!');
+               $this->denyAccessUnlessGranted('ROLE_ADMIN', null, $this->translator->trans('Unable to access this page without role %role%!', ['%role%' => $this->translator->trans('Admin')]));
 
 
-               //Set section
-               $section = $this->translator->trans('Admin');
+               //Get doctrine
+               $doctrine = $this->getDoctrine();
 
 
-               //Set title
-               $title = $section.' - '.$this->translator->trans($this->config['site']['title']);
-
-               header('Content-Type: text/plain');
-               var_dump('TODO');
-               exit;
-               //Create the form according to the FormType created previously.
-               //And give the proper parameters
-               $form = $this->createForm('Rapsys\AirBundle\Form\ApplicationType', null, [
-                       // To set the action use $this->generateUrl('route_identifier')
-                       'action' => $this->generateUrl('rapsys_air_admin'),
-                       'method' => 'POST',
-                       'attr' => [ 'class' => 'form_col' ]
+               //Get location
+               if (empty($location = $doctrine->getRepository(Location::class)->findOneById($id))) {
+                       throw $this->createNotFoundException($this->translator->trans('Unable to find location: %id%', ['%id%' => $id]));
+               }
+
+               //Create LocationType form
+               $form = $this->createForm('Rapsys\AirBundle\Form\LocationType', $location, [
+                       //Set the action
+                       'action' => $this->generateUrl('rapsys_air_location_edit', ['id' => $id]),
+                       //Set the form attribute
+                       'attr' => []
                ]);
 
                ]);
 
-               //Get doctrine
-               $doctrine = $this->getDoctrine();
+               //Refill the fields in case of invalid form
+               $form->handleRequest($request);
 
 
-               //Handle request
-               if ($request->isMethod('POST')) {
-                       // Refill the fields in case the form is not valid.
-                       $form->handleRequest($request);
-
-                       if ($form->isValid()) {
-                               //Get data
-                               $data = $form->getData();
-
-                               //Get manager
-                               $manager = $doctrine->getManager();
-
-                               //Protect session fetching
-                               try {
-                                       $session = $doctrine->getRepository(Session::class)->findOneByLocationSlotDate($data['location'], $data['slot'], $data['date']);
-                               //Catch no session case
-                               } catch (\Doctrine\ORM\NoResultException $e) {
-                                       //Create the session
-                                       $session = new Session();
-                                       $session->setLocation($data['location']);
-                                       $session->setSlot($data['slot']);
-                                       $session->setDate($data['date']);
-                                       $session->setCreated(new \DateTime('now'));
-                                       $session->setUpdated(new \DateTime('now'));
-                                       $manager->persist($session);
-                                       //Flush to get the ids
-                                       #$manager->flush();
-                               }
+               //Handle invalid form
+               if (!$form->isSubmitted() || !$form->isValid()) {
+                       //Set section
+                       $section = $this->translator->trans('Location %id%', ['%id%' => $id]);
 
 
-                               //Init application
-                               $application = false;
-
-                               //Protect application fetching
-                               try {
-                                       //TODO: handle admin case where we provide a user in extra
-                                       $application = $doctrine->getRepository(Application::class)->findOneBySessionUser($session, $this->getUser());
-
-                                       //Add error message to mail field
-                                       $form->get('slot')->addError(new FormError($this->translator->trans('Application already exists')));
-                               //Catch no application cases
-                               //XXX: combine these catch when php 7.1 is available
-                               } catch (\Doctrine\ORM\NoResultException $e) {
-                               //Catch invalid argument because session is not already persisted
-                               } catch(\Doctrine\ORM\ORMInvalidArgumentException $e) {
-                               }
+                       //Set title
+                       $title = $this->translator->trans($this->config['site']['title']).' - '.$section;
+
+                       //Render the view
+                       return $this->render('@RapsysAir/location/edit.html.twig', ['id' => $id, 'title' => $title, 'section' => $section, 'form' => $form->createView()]+$this->context);
+               }
+
+               //Get manager
+               $manager = $doctrine->getManager();
+
+               //Set updated
+               $location->setUpdated(new \DateTime('now'));
+
+               //Queue location save
+               $manager->persist($location);
+
+               //Flush to get the ids
+               $manager->flush();
+
+               //Add notice
+               $this->addFlash('notice', $this->translator->trans('Location %id% updated', ['%id%' => $id]));
+
+               //Extract and process referer
+               if ($referer = $request->headers->get('referer')) {
+                       //Create referer request instance
+                       $req = Request::create($referer);
+
+                       //Get referer path
+                       $path = $req->getPathInfo();
+
+                       //Get referer query string
+                       $query = $req->getQueryString();
 
 
-                               //Create new application if none found
-                               if (!$application) {
-                                       //Create the application
-                                       $application = new Application();
-                                       $application->setSession($session);
-                                       //TODO: handle admin case where we provide a user in extra
-                                       $application->setUser($this->getUser());
-                                       $application->setCreated(new \DateTime('now'));
-                                       $application->setUpdated(new \DateTime('now'));
-                                       $manager->persist($application);
-
-                                       //Flush to get the ids
-                                       $manager->flush();
-
-                                       //Add notice in flash message
-                                       $this->addFlash('notice', $this->translator->trans('Application request the %date% for %location% on the slot %slot% saved', ['%location%' => $data['location']->getTitle(), '%slot%' => $data['slot']->getTitle(), '%date%' => $data['date']->format('Y-m-d')]));
-
-                                       //Redirect to cleanup the form
-                                       return $this->redirectToRoute('rapsys_air_admin');
+                       //Remove script name
+                       $path = str_replace($request->getScriptName(), '', $path);
+
+                       //Try with referer path
+                       try {
+                               //Save old context
+                               $oldContext = $this->router->getContext();
+
+                               //Force clean context
+                               //XXX: prevent MethodNotAllowedException because current context method is POST in onevendor/symfony/routing/Matcher/Dumper/CompiledUrlMatcherTrait.php+42
+                               $this->router->setContext(new RequestContext());
+
+                               //Retrieve route matching path
+                               $route = $this->router->match($path);
+
+                               //Reset context
+                               $this->router->setContext($oldContext);
+
+                               //Clear old context
+                               unset($oldContext);
+
+                               //Extract name
+                               $name = $route['_route'];
+
+                               //Remove route and controller from route defaults
+                               unset($route['_route'], $route['_controller']);
+
+                               //Check if location view route
+                               if ($name == 'rapsys_air_location_view' && !empty($route['id'])) {
+                                       //Replace id
+                                       $route['id'] = $location->getId();
+                               //Other routes
+                               } else {
+                                       //Set location
+                                       $route['location'] = $location->getId();
                                }
                                }
+
+                               //Generate url
+                               return $this->redirectToRoute($name, $route);
+                       //No route matched
+                       } catch(MethodNotAllowedException|ResourceNotFoundException $e) {
+                               //Unset referer to fallback to default route
+                               unset($referer);
                        }
                }
 
                        }
                }
 
+               //Redirect to cleanup the form
+               return $this->redirectToRoute('rapsys_air', ['location' => $location->getId()]);
+       }
+
+       /**
+        * List all locations
+        *
+        * @desc Display all locations
+        *
+        * @param Request $request The request instance
+        *
+        * @return Response The rendered view
+        */
+       public function index(Request $request): Response {
+               //Fetch doctrine
+               $doctrine = $this->getDoctrine();
+
+               //Set section
+               $section = $this->translator->trans('Libre Air locations');
+
+               //Set description
+               $this->context['description'] = $this->translator->trans('Libre Air location list');
+
+               //Set keywords
+               $this->context['keywords'] = [
+                       $this->translator->trans('locations'),
+                       $this->translator->trans('location list'),
+                       $this->translator->trans('listing'),
+                       $this->translator->trans('Libre Air')
+               ];
+
+               //Set title
+               $title = $this->translator->trans($this->config['site']['title']).' - '.$section;
+
                //Compute period
                $period = new \DatePeriod(
                        //Start from first monday of week
                //Compute period
                $period = new \DatePeriod(
                        //Start from first monday of week
@@ -170,107 +294,139 @@ class LocationController extends DefaultController {
                        //Iterate on each day
                        new \DateInterval('P1D'),
                        //End with next sunday and 4 weeks
                        //Iterate on each day
                        new \DateInterval('P1D'),
                        //End with next sunday and 4 weeks
-                       new \DateTime('Monday this week + 5 week')
+                       new \DateTime(
+                               $this->isGranted('IS_AUTHENTICATED_REMEMBERED')?'Monday this week + 3 week':'Monday this week + 2 week'
+                       )
                );
 
                );
 
-               //Fetch sessions
-               $sessions = $doctrine->getRepository(Session::class)->findAllByDatePeriod($period);
-
-               //Init calendar
-               $calendar = [];
-               
-               //Init month
-               $month = null;
-
-               //Iterate on each day
-               foreach($period as $date) {
-                       //Init day in calendar
-                       $calendar[$Ymd = $date->format('Ymd')] = [
-                               'title' => $date->format('d'),
-                               'class' => [],
-                               'sessions' => []
-                       ];
-                       //Append month for first day of month
-                       if ($month != $date->format('m')) {
-                               $month = $date->format('m');
-                               $calendar[$Ymd]['title'] .= '/'.$month;
-                       }
-                       //Deal with today
-                       if ($date->format('U') == ($today = strtotime('today'))) {
-                               $calendar[$Ymd]['title'] .= '/'.$month;
-                               $calendar[$Ymd]['current'] = true;
-                               $calendar[$Ymd]['class'][] =  'current';
-                       }
-                       //Disable passed days
-                       if ($date->format('U') < $today) {
-                               $calendar[$Ymd]['disabled'] = true;
-                               $calendar[$Ymd]['class'][] =  'disabled';
-                       }
-                       //Set next month days
-                       if ($date->format('m') > date('m')) {
-                               $calendar[$Ymd]['next'] = true;
-                               $calendar[$Ymd]['class'][] =  'next';
-                       }
-                       //Iterate on each session to find the one of the day
-                       foreach($sessions as $session) {
-                               if (($sessionYmd = $session->getDate()->format('Ymd')) == $Ymd) {
-                                       //Count number of application
-                                       $count = count($session->getApplications());
-
-                                       //Compute classes
-                                       $class = [];
-                                       if ($session->getApplication()) {
-                                               $class[] = 'granted';
-                                       } elseif ($count == 0) {
-                                               $class[] = 'orphaned';
-                                       } elseif ($count > 1) {
-                                               $class[] = 'disputed';
-                                       } else {
-                                               $class[] = 'pending';
-                                       }
-
-                                       //Add the session
-                                       $calendar[$Ymd]['sessions'][$session->getSlot()->getId().$session->getLocation()->getId()] = [
-                                               'id' => $session->getId(),
-                                               'title' => ($count > 1?'['.$count.'] ':'').$session->getSlot()->getTitle().' '.$session->getLocation()->getTitle(),
-                                               'class' => $class
-                                       ];
-                               }
+               //Create location forms for role_admin
+               if ($this->isGranted('ROLE_ADMIN')) {
+                       //Fetch all locations
+                       $locations = $doctrine->getRepository(Location::class)->findAll();
+
+                       //Rekey by id
+                       $locations = array_reduce($locations, function($carry, $item){$carry[$item->getId()] = $item; return $carry;}, []);
+
+                       //Init locations to context
+                       $this->context['forms']['locations'] = [];
+
+                       //Iterate on locations
+                       foreach($locations as $locationId => $location) {
+                               //Create LocationType form
+                               $form = $this->createForm('Rapsys\AirBundle\Form\LocationType', $location, [
+                                       //Set the action
+                                       'action' => $this->generateUrl('rapsys_air_location_edit', ['id' => $location->getId()]),
+                                       //Set the form attribute
+                                       'attr' => [],
+                                       //Set block prefix
+                                       //TODO: make this shit works to prevent label collision
+                                       //XXX: see https://stackoverflow.com/questions/8703016/adding-a-prefix-to-a-form-label-for-translation
+                                       'label_prefix' => 'location_'.$locationId
+                               ]);
+
+                               //Add form to context
+                               $this->context['forms']['locations'][$locationId] = $form->createView();
                        }
 
                        }
 
-                       //Sort sessions
-                       ksort($calendar[$Ymd]['sessions']);
+                       //Create LocationType form
+                       $form = $this->createForm('Rapsys\AirBundle\Form\LocationType', null, [
+                               //Set the action
+                               'action' => $this->generateUrl('rapsys_air_location_add'),
+                               //Set the form attribute
+                               'attr' => [ 'class' => 'col' ]
+                       ]);
+
+                       //Add form to context
+                       $this->context['forms']['location'] = $form->createView();
                }
 
                }
 
-               return $this->render('@RapsysAir/admin/index.html.twig', ['title' => $title, 'section' => $section, 'form' => $form->createView(), 'calendar' => $calendar]);
+               //Fetch locations
+               //XXX: we want to display all active locations anyway
+               $locations = $doctrine->getRepository(Location::class)->findTranslatedSortedByPeriod($this->translator, $period);
+
+               //Render the view
+               return $this->render('@RapsysAir/location/index.html.twig', ['title' => $title, 'section' => $section, 'locations' => $locations]+$this->context);
        }
 
        }
 
-       public function tata(Request $request, $id) {
-               /*header('Content-Type: text/plain');
-               var_dump($calendar);
-               exit;*/
+       /**
+        * List all sessions for the location
+        *
+        * @desc Display all sessions for the location with an application or login form
+        *
+        * @param Request $request The request instance
+        * @param int $id The location id
+        *
+        * @return Response The rendered view
+        */
+       public function view(Request $request, $id): Response {
+               //Fetch doctrine
+               $doctrine = $this->getDoctrine();
+
+               //Fetch location
+               if (empty($location = $doctrine->getRepository(Location::class)->findOneById($id))) {
+                       throw $this->createNotFoundException($this->translator->trans('Unable to find location: %id%', ['%id%' => $id]));
+               }
 
                //Set section
 
                //Set section
-               $section = $this->translator->trans('Session %id%', ['%id%' => $id]);
+               $section = $this->translator->trans('Argentine Tango at '.$location);
+
+               //Set description
+               $this->context['description'] = $this->translator->trans('Outdoor Argentine Tango session calendar %location%', [ '%location%' => $this->translator->trans('at '.$location) ]);
+
+               //Set keywords
+               $this->context['keywords'] = [
+                       $this->translator->trans($location),
+                       $this->translator->trans('outdoor'),
+                       $this->translator->trans('Argentine Tango'),
+                       $this->translator->trans('calendar')
+               ];
 
                //Set title
 
                //Set title
-               $title = $section.' - '.$this->translator->trans($this->config['site']['title']);
+               $title = $this->translator->trans($this->config['site']['title']).' - '.$section;
 
 
-               //Create the form according to the FormType created previously.
-               //And give the proper parameters
-               /*$form = $this->createForm('Rapsys\AirBundle\Form\ApplicationType', null, [
-                       // To set the action use $this->generateUrl('route_identifier')
-                       'action' => $this->generateUrl('rapsys_air_admin'),
-                       'method' => 'POST',
-                       'attr' => [ 'class' => 'form_col' ]
-               ]);*/
+               //Create application form for role_guest
+               if ($this->isGranted('ROLE_GUEST')) {
+                       //Create ApplicationType form
+                       $application = $this->createForm('Rapsys\AirBundle\Form\ApplicationType', null, [
+                               //Set the action
+                               'action' => $this->generateUrl('rapsys_air_application_add'),
+                               //Set the form attribute
+                               'attr' => [ 'class' => 'col' ],
+                               //Set admin
+                               'admin' => $this->isGranted('ROLE_ADMIN'),
+                               //Set default user to current
+                               'user' => $this->getUser()->getId(),
+                               //Set default slot to evening
+                               //XXX: default to Evening (3)
+                               'slot' => $doctrine->getRepository(Slot::class)->findOneById(3),
+                               //Set default location to current one
+                               'location' => $location
+                       ]);
 
 
-               //Get doctrine
-               $doctrine = $this->getDoctrine();
+                       //Add form to context
+                       $this->context['forms']['application'] = $application->createView();
+               }
+
+               //Compute period
+               $period = new \DatePeriod(
+                       //Start from first monday of week
+                       new \DateTime('Monday this week'),
+                       //Iterate on each day
+                       new \DateInterval('P1D'),
+                       //End with next sunday and 4 weeks
+                       new \DateTime(
+                               $this->isGranted('IS_AUTHENTICATED_REMEMBERED')?'Monday this week + 3 week':'Monday this week + 2 week'
+                       )
+               );
 
 
-               //Fetch session
-               $session = $doctrine->getRepository(Session::class)->findOneById($id);
+               //Fetch calendar
+               $calendar = $doctrine->getRepository(Session::class)->fetchCalendarByDatePeriod($this->translator, $period, $id, $request->get('session'), !$this->isGranted('IS_AUTHENTICATED_REMEMBERED'));
 
 
-               return $this->render('@RapsysAir/admin/session.html.twig', ['title' => $title, 'section' => $section, /*'form' => $form->createView(),*/ 'session' => $session]);
+               //Fetch locations
+               //XXX: we want to display all active locations anyway
+               $locations = $doctrine->getRepository(Location::class)->findTranslatedSortedByPeriod($this->translator, $period);
+
+               //Render the view
+               return $this->render('@RapsysAir/location/view.html.twig', ['id' => $id, 'title' => $title, 'section' => $section, 'calendar' => $calendar, 'locations' => $locations]+$this->context);
        }
 }
        }
 }