X-Git-Url: https://git.rapsys.eu/airbundle/blobdiff_plain/dbdbad6ce85340b0ed2e9a6cbfb35e547200cdd6..c435a53cb44704beddd9d5dbb668b0e2781cf91c:/Controller/LocationController.php?ds=inline diff --git a/Controller/LocationController.php b/Controller/LocationController.php index ad28644..8838d69 100644 --- a/Controller/LocationController.php +++ b/Controller/LocationController.php @@ -1,276 +1,512 @@ - + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ namespace Rapsys\AirBundle\Controller; use Symfony\Component\HttpFoundation\Request; -use Rapsys\AirBundle\Entity\Slot; +use Symfony\Component\HttpFoundation\Response; + +use Rapsys\AirBundle\Entity\Dance; +use Rapsys\AirBundle\Entity\Location; +use Rapsys\AirBundle\Entity\Session; +/** + * {@inheritdoc} + */ class LocationController extends DefaultController { /** - * List all locations - * - * @desc Display all sessions by location with an application or login form + * List all cities * * @param Request $request The request instance - * * @return Response The rendered view */ - public function index(Request $request = null) { - //Set section - $section = $this->translator->trans('Locations'); + public function cities(Request $request): Response { + //Add cities + $this->context['cities'] = $this->doctrine->getRepository(Location::class)->findCitiesAsArray($this->period, 0); - //Set title - $title = $section.' - '.$this->translator->trans($this->config['site']['title']); - - //Init context - $context = []; - - //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')])) - ]); + //Add dances + $this->context['dances'] = $this->doctrine->getRepository(Dance::class)->findNamesAsArray(); - //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' ] - ]); + //Create response + $response = new Response(); - //Add form to context - $context['login'] = $login->createView(); + //Set modified + $this->modified = max(array_map(function ($v) { return $v['modified']; }, array_merge($this->context['cities'], $this->context['dances']))); + + //Add city multi + foreach($this->context['cities'] as $id => $city) { + //Add city multi + $this->context['cities'][$id]['multimap'] = $this->map->getMultiMap($city['multimap'], $this->modified->getTimestamp(), $city['locations']); } - $calendar = 'toto'; + //With logged user + if ($this->isGranted('IS_AUTHENTICATED_REMEMBERED')) { + //Set last modified + $response->setLastModified(new \DateTime('-1 year')); + + //Set as private + $response->setPrivate(); + //Without logged user + } else { + //Set etag + //XXX: only for public to force revalidation by last modified + $response->setEtag(md5(serialize(array_merge($this->context['cities'], $this->context['dances'])))); + + //Set last modified + $response->setLastModified($this->modified); + + //Set as public + $response->setPublic(); + + //Without role and modification + if ($response->isNotModified($request)) { + //Return 304 response + return $response; + } + } + + //Set section + $this->context['title'] = $this->translator->trans('Libre Air cities'); + + //Set description + $this->context['description'] = $this->translator->trans('Libre Air city list'); + + //Set cities + $cities = array_map(function ($v) { return $v['in']; }, $this->context['cities']); + + //Set dances + $dances = array_map(function ($v) { return $v['name']; }, $this->context['dances']); + + //Set indoors + $indoors = array_reduce($this->context['cities'], function ($c, $v) { return array_merge($c, $v['indoors']); }, []); + + //Set keywords + $this->context['keywords'] = array_values( + array_merge( + [ + $this->translator->trans('Cities'), + $this->translator->trans('City list'), + $this->translator->trans('Listing'), + ], + $cities, + $indoors, + [ + $this->translator->trans('calendar'), + $this->translator->trans('Libre Air') + ] + ) + ); //Render the view - return $this->render('@RapsysAir/location/index.html.twig', ['title' => $title, 'section' => $section, 'calendar' => $calendar]+$context+$this->context); + return $this->render('@RapsysAir/location/cities.html.twig', $this->context, $response); } - public function show(Request $request, $id) { + /** + * Display city + * + * @todo XXX: TODO: add + * @todo XXX: TODO: like described in: https://www.alsacreations.com/article/lire/1400-attribut-rel-relations.html#xnf-rel-attribute + * @todo XXX: TODO: or here: http://microformats.org/wiki/existing-rel-values#HTML5_link_type_extensions + * + * @param Request $request The request instance + * @param float $latitude The city latitude + * @param float $longitude The city longitude + * @return Response The rendered view + */ + public function city(Request $request, float $latitude, float $longitude, string $city): Response { + //Get city + if (!($this->context['city'] = $this->doctrine->getRepository(Location::class)->findCityByLatitudeLongitudeAsArray(floatval($latitude), floatval($longitude)))) { + throw $this->createNotFoundException($this->translator->trans('Unable to find city: %latitude%,%longitude%', ['%latitude%' => $latitude, '%longitude%' => $longitude])); + } + + //Add calendar + $this->context['calendar'] = $this->doctrine->getRepository(Session::class)->findAllByPeriodAsCalendarArray($this->period, !$this->isGranted('IS_AUTHENTICATED_REMEMBERED'), floatval($latitude), floatval($longitude)); + + //Set dances + $this->context['dances'] = []; + + //Iterate on each calendar + foreach($this->context['calendar'] as $date => $calendar) { + //Iterate on each session + foreach($calendar['sessions'] as $sessionId => $session) { + //Session with application dance + if (!empty($session['application']['dance'])) { + //Add dance + $this->context['dances'][$session['application']['dance']['id']] = $session['application']['dance']; + } + } + } + + //Add locations + $this->context['locations'] = $this->doctrine->getRepository(Location::class)->findAllByLatitudeLongitudeAsArray(floatval($latitude), floatval($longitude), $this->period, 0); + + //Set modified + //XXX: dance modified is already computed inside calendar modified + $this->modified = max(array_merge([$this->context['city']['updated']], array_map(function ($v) { return $v['modified']; }, array_merge($this->context['calendar'], $this->context['locations'])))); + + //Create response + $response = new Response(); + + //With logged user + if ($this->isGranted('IS_AUTHENTICATED_REMEMBERED')) { + //Set last modified + $response->setLastModified(new \DateTime('-1 year')); + + //Set as private + $response->setPrivate(); + //Without logged user + } else { + //Set etag + //XXX: only for public to force revalidation by last modified + $response->setEtag(md5(serialize(array_merge($this->context['city'], $this->context['dances'], $this->context['calendar'], $this->context['locations'])))); + + //Set last modified + $response->setLastModified($this->modified); + + //Set as public + $response->setPublic(); + + //Without role and modification + if ($response->isNotModified($request)) { + //Return 304 response + return $response; + } + } + + //Add multi + $this->context['multimap'] = $this->map->getMultiMap($this->context['city']['multimap'], $this->modified->getTimestamp(), $this->context['locations']); + + //Set keywords + $this->context['keywords'] = [ + $this->context['city']['city'], + $this->translator->trans('Indoor'), + $this->translator->trans('Outdoor'), + $this->translator->trans('Calendar'), + $this->translator->trans('Libre Air') + ]; + + //With context dances + if (!empty($this->context['dances'])) { + //Set dances + $dances = array_map(function ($v) { return $v['name']; }, $this->context['dances']); + + //Insert dances in keywords + array_splice($this->context['keywords'], 1, 0, $dances); + + //Get textual dances + $dances = implode($this->translator->trans(' and '), array_filter(array_merge([implode(', ', array_slice($dances, 0, -1))], array_slice($dances, -1)), 'strlen')); + + //Set title + $this->context['title'] = $this->translator->trans('%dances% %city%', ['%dances%' => $dances, '%city%' => $this->context['city']['in']]); + + //Set description + $this->context['description'] = $this->translator->trans('%dances% indoor and outdoor calendar %city%', ['%dances%' => $dances, '%city%' => $this->context['city']['in']]); + } else { + //Set title + $this->context['title'] = $this->translator->trans('Dance %city%', ['%city%' => $this->context['city']['in']]); + + //Set description + $this->context['description'] = $this->translator->trans('Indoor and outdoor dance calendar %city%', ['%city%' => $this->context['city']['in']]); + } + + //Set locations description + $this->context['locations_description'] = $this->translator->trans('Libre Air location list %city%', ['%city%' => $this->context['city']['in']]); + + //Render the view + return $this->render('@RapsysAir/location/city.html.twig', $this->context, $response); } - public function toto(Request $request) { - //Prevent non-admin to access here - $this->denyAccessUnlessGranted('ROLE_GUEST', null, 'Unable to access this page without ROLE_GUEST!'); + /** + * List all locations + * + * @desc Display all locations + * + * @param Request $request The request instance + * + * @return Response The rendered view + */ + public function index(Request $request): Response { + //Get locations + $this->context['locations'] = $this->doctrine->getRepository(Location::class)->findAllAsArray($this->period); + + //Set modified + $this->modified = max(array_map(function ($v) { return $v['updated']; }, $this->context['locations'])); + + //Create response + $response = new Response(); + + //With logged user + if ($this->isGranted('IS_AUTHENTICATED_REMEMBERED')) { + //Set last modified + $response->setLastModified(new \DateTime('-1 year')); + + //Set as private + $response->setPrivate(); + //Without logged user + } else { + //Set etag + //XXX: only for public to force revalidation by last modified + $response->setEtag(md5(serialize($this->context['locations']))); + + //Set last modified + $response->setLastModified($this->modified); + + //Set as public + $response->setPublic(); + + //Without role and modification + if ($response->isNotModified($request)) { + //Return 304 response + return $response; + } + } - //Set section - $section = $this->translator->trans('Admin'); + //Add multi map + $this->context['multimap'] = $this->map->getMultiMap($this->translator->trans('Libre Air locations sector map'), $this->modified->getTimestamp(), $this->context['locations']); //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 doctrine - $doctrine = $this->getDoctrine(); - - //Handle request - if ($request->isMethod('POST')) { - // Refill the fields in case the form is not valid. + $this->context['title'] = $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') + ]; + + //Create location forms for role_admin + if ($this->isGranted('ROLE_ADMIN')) { + //Fetch all locations + $locations = $this->doctrine->getRepository(Location::class)->findAll(); + + //Init locations to context + $this->context['forms']['locations'] = []; + + //Iterate on locations + foreach($this->context['locations'] as $id => $location) { + //Create LocationType form + $form = $this->factory->createNamed( + //Set form id + 'locations_'.$id, + //Set form type + 'Rapsys\AirBundle\Form\LocationType', + //Set form data + $locations[$location['id']], + //Set the form attributes + ['attr' => []] + ); + + //Refill the fields in case of invalid form + $form->handleRequest($request); + + //Handle valid form + if ($form->isSubmitted() && $form->isValid()) { + //Get data + $data = $form->getData(); + + //Set updated + $data->setUpdated(new \DateTime('now')); + + //Queue location save + $this->manager->persist($data); + + //Flush to get the ids + $this->manager->flush(); + + //Add notice + $this->addFlash('notice', $this->translator->trans('Location %id% updated', ['%id%' => $location['id']])); + + //Redirect to cleanup the form + return $this->redirectToRoute('rapsys_air_location', ['location' => $location['id']]); + } + + //Add form to context + $this->context['forms']['locations'][$id] = $form->createView(); + } + + //Create LocationType form + $form = $this->factory->createNamed( + //Set form id + 'locations', + //Set form type + 'Rapsys\AirBundle\Form\LocationType', + //Set form data + new Location(), + //Set the form attributes + ['attr' => ['class' => 'col']] + ); + + //Refill the fields in case of invalid form $form->handleRequest($request); - if ($form->isValid()) { + //Handle valid form + if ($form->isSubmitted() && $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(); - } + //Queue location save + $this->manager->persist($data); - //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) { - } + //Flush to get the ids + $this->manager->flush(); - //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); + //Add notice + $this->addFlash('notice', $this->translator->trans('Location created')); - //Flush to get the ids - $manager->flush(); + //Redirect to cleanup the form + return $this->redirectToRoute('rapsys_air_location', ['location' => $data->getId()]); + } - //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')])); + //Add form to context + $this->context['forms']['location'] = $form->createView(); + } - //Redirect to cleanup the form - return $this->redirectToRoute('rapsys_air_admin'); - } - } + //Render the view + return $this->render('@RapsysAir/location/index.html.twig', $this->context); + } + + /** + * List all sessions for the location + * + * Display all sessions for the location with an application or login form + * + * @TODO: add location edit form ??? + * + * @param Request $request The request instance + * @param int $id The location id + * @param ?string $location The location slug + * + * @return Response The rendered view + */ + public function view(Request $request, int $id, ?string $location): Response { + //Without location + if (empty($this->context['location'] = $this->doctrine->getRepository(Location::class)->findOneByIdAsArray($id, $this->locale))) { + //Throw 404 + throw $this->createNotFoundException($this->translator->trans('Unable to find location: %id%', ['%id%' => $id])); } - //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('Monday this week + 5 week') - ); + //With invalid slug + if ($location !== $this->context['location']['slug']) { + //Redirect on correctly spelled location + return $this->redirectToRoute('rapsys_air_location_view', ['id' => $this->context['location']['id'], 'location' => $this->context['location']['slug']], Response::HTTP_MOVED_PERMANENTLY); + } - //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 - ]; + //Fetch calendar + $this->context['calendar'] = $this->doctrine->getRepository(Session::class)->findAllByPeriodAsCalendarArray($this->period, !$this->isGranted('IS_AUTHENTICATED_REMEMBERED'), $this->context['location']['latitude'], $this->context['location']['longitude']); + + //Set dances + $this->context['dances'] = []; + + //Iterate on each calendar + foreach($this->context['calendar'] as $date => $calendar) { + //Iterate on each session + foreach($calendar['sessions'] as $sessionId => $session) { + //Session with application dance + if (!empty($session['application']['dance'])) { + //Add dance + $this->context['dances'][$session['application']['dance']['id']] = $session['application']['dance']; } } - - //Sort sessions - ksort($calendar[$Ymd]['sessions']); } - return $this->render('@RapsysAir/admin/index.html.twig', ['title' => $title, 'section' => $section, 'form' => $form->createView(), 'calendar' => $calendar]); - } + //Get locations at less than 2 km + $this->context['locations'] = $this->doctrine->getRepository(Location::class)->findAllByLatitudeLongitudeAsArray($this->context['location']['latitude'], $this->context['location']['longitude'], $this->period, 2); - public function tata(Request $request, $id) { - /*header('Content-Type: text/plain'); - var_dump($calendar); - exit;*/ + //Set modified + //XXX: dance modified is already computed inside calendar modified + $this->modified = max(array_merge([$this->context['location']['updated']], array_map(function ($v) { return $v['modified']; }, array_merge($this->context['calendar'], $this->context['locations'])))); - //Set section - $section = $this->translator->trans('Session %id%', ['%id%' => $id]); + //Create response + $response = new Response(); - //Set title - $title = $section.' - '.$this->translator->trans($this->config['site']['title']); + //With logged user + if ($this->isGranted('IS_AUTHENTICATED_REMEMBERED')) { + //Set last modified + $response->setLastModified(new \DateTime('-1 year')); + + //Set as private + $response->setPrivate(); + //Without logged user + } else { + //Set etag + //XXX: only for public to force revalidation by last modified + $response->setEtag(md5(serialize(array_merge($this->context['location'], $this->context['calendar'], $this->context['locations'])))); + + //Set last modified + $response->setLastModified($this->modified); + + //Set as public + $response->setPublic(); - //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' ] - ]);*/ + //Without role and modification + if ($response->isNotModified($request)) { + //Return 304 response + return $response; + } + } + + //Add multi map + $this->context['multimap'] = $this->map->getMultiMap($this->context['location']['multimap'], $this->modified->getTimestamp(), $this->context['locations']); + + //Set keywords + $this->context['keywords'] = [ + $this->context['location']['title'], + $this->context['location']['city']['title'], + $this->translator->trans($this->context['location']['indoor']?'Indoor':'Outdoor'), + $this->translator->trans('Calendar'), + $this->translator->trans('Libre Air') + ]; + + //With dances + if (!empty($this->context['dances'])) { + //Set dances + $dances = array_map(function ($v) { return $v['name']; }, $this->context['dances']); + + //Insert dances in keywords + array_splice($this->context['keywords'], 2, 0, $dances); + + //Get textual dances + $dances = implode($this->translator->trans(' and '), array_filter(array_merge([implode(', ', array_slice($dances, 0, -1))], array_slice($dances, -1)), 'strlen')); + + //Set title + $this->context['title'] = $this->translator->trans('%dances% %location%', ['%dances%' => $dances, '%location%' => $this->context['location']['atin']]); + + //Set description + $this->context['description'] = $this->translator->trans('%dances% indoor and outdoor calendar %location%', ['%dances%' => $dances, '%location%' => $this->context['location']['at']]); + //Without dances + } else { + //Set title + $this->context['title'] = $this->translator->trans('Dance %location%', ['%location%' => $this->context['location']['atin']]); + + //Set description + $this->context['description'] = $this->translator->trans('Indoor and outdoor dance calendar %location%', ['%location%' => $this->context['location']['at']]); + } - //Get doctrine - $doctrine = $this->getDoctrine(); + //Set locations description + $this->context['locations_description'] = $this->translator->trans('Libre Air location list %location% %city%', ['%location%' => $this->context['location']['around'], '%city%' => $this->context['location']['city']['in']]); - //Fetch session - $session = $doctrine->getRepository(Session::class)->findOneById($id); + //Set locations link + $this->context['locations_link'] = $this->context['location']['city']['link']; - return $this->render('@RapsysAir/admin/session.html.twig', ['title' => $title, 'section' => $section, /*'form' => $form->createView(),*/ 'session' => $session]); + //Set locations title + $this->context['locations_title'] = $this->context['location']['city']['title'].' ('.$this->context['location']['city']['id'].')'; + + //Set alternates + $this->context['alternates'] += $this->context['location']['alternates']; + + //Render the view + return $this->render('@RapsysAir/location/view.html.twig', $this->context, $response); } }