]> Raphaël G. Git Repositories - airbundle/blob - Controller/ApplicationController.php
List dance sessions
[airbundle] / Controller / ApplicationController.php
1 <?php declare(strict_types=1);
2
3 /*
4 * This file is part of the Rapsys AirBundle package.
5 *
6 * (c) Raphaël Gertz <symfony@rapsys.eu>
7 *
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
10 */
11
12 namespace Rapsys\AirBundle\Controller;
13
14 use Doctrine\ORM\NoResultException;
15 use Doctrine\ORM\ORMInvalidArgumentException;
16 use Symfony\Component\Form\FormError;
17 use Symfony\Component\HttpFoundation\Request;
18 use Symfony\Component\HttpFoundation\Response;
19 use Symfony\Component\Routing\Exception\MethodNotAllowedException;
20 use Symfony\Component\Routing\Exception\ResourceNotFoundException;
21 use Symfony\Component\Routing\RequestContext;
22
23 use Rapsys\AirBundle\Entity\Application;
24 use Rapsys\AirBundle\Entity\Dance;
25 use Rapsys\AirBundle\Entity\Location;
26 use Rapsys\AirBundle\Entity\Session;
27 use Rapsys\AirBundle\Entity\Slot;
28 use Rapsys\AirBundle\Entity\User;
29
30 /**
31 * {@inheritdoc}
32 */
33 class ApplicationController extends AbstractController {
34 /**
35 * Add application
36 *
37 * Persist application and all required dependencies in database
38 *
39 * @param Request $request The request instance
40 * @param Registry $manager The doctrine registry
41 * @param EntityManagerInterface $manager The doctrine entity manager
42 *
43 * @return Response The rendered view or redirection
44 *
45 * @throws \RuntimeException When user has not at least guest role
46 */
47 public function add(Request $request) {
48 //Without guest role
49 if (!$this->checker->isGranted('ROLE_GUEST')) {
50 //Throw 403
51 throw $this->createAccessDeniedException($this->translator->trans('Unable to access this page without role %role%!', ['%role%' => $this->translator->trans('Guest')]));
52 }
53
54 //Get favorites dances
55 $danceFavorites = $this->doctrine->getRepository(Dance::class)->findByUserId($this->security->getUser()->getId());
56
57 //Set dance default
58 $danceDefault = !empty($danceFavorites)?current($danceFavorites):null;
59
60 //Get favorites locations
61 $locationFavorites = $this->doctrine->getRepository(Location::class)->findByUserId($this->security->getUser()->getId());
62
63 //Set location default
64 $locationDefault = !empty($locationFavorites)?current($locationFavorites):null;
65
66 //With admin
67 if ($this->checker->isGranted('ROLE_ADMIN')) {
68 //Get dances
69 $dances = $this->doctrine->getRepository(Dance::class)->findAll();
70
71 //Get locations
72 $locations = $this->doctrine->getRepository(Location::class)->findAll();
73 //Without admin
74 } else {
75 //Restrict to favorite dances
76 $dances = $danceFavorites;
77
78 //Reset favorites
79 $danceFavorites = [];
80
81 //Restrict to favorite locations
82 $locations = $locationFavorites;
83
84 //Reset favorites
85 $locationFavorites = [];
86 }
87
88 //Create ApplicationType form
89 $form = $this->factory->create('Rapsys\AirBundle\Form\ApplicationType', null, [
90 //Set the action
91 'action' => $this->generateUrl('rapsysair_application_add'),
92 //Set the form attribute
93 #'attr' => [ 'class' => 'col' ],
94 //Set dance choices
95 'dance_choices' => $dances,
96 //Set dance default
97 'dance_default' => $danceDefault,
98 //Set dance favorites
99 'dance_favorites' => $danceFavorites,
100 //Set location choices
101 'location_choices' => $locations,
102 //Set location default
103 'location_default' => $locationDefault,
104 //Set location favorites
105 'location_favorites' => $locationFavorites,
106 //With user
107 'user' => $this->checker->isGranted('ROLE_ADMIN'),
108 //Set user choices
109 'user_choices' => $this->doctrine->getRepository(User::class)->findChoicesAsArray(),
110 //Set default user to current
111 'user_default' => $this->security->getUser()->getId(),
112 //Set default slot to evening
113 //XXX: default to Evening (3)
114 'slot_default' => $this->doctrine->getRepository(Slot::class)->findOneByTitle('Evening')
115 ]);
116
117 //Set title
118 $this->context['title']['page'] = $this->translator->trans('Application add');
119
120 //Set section
121 $this->context['title']['section'] = $this->translator->trans('Application');
122
123 //Set description
124 $this->context['description'] = $this->translator->trans('Add an application and session');
125
126 //Refill the fields in case of invalid form
127 $form->handleRequest($request);
128
129 //Handle invalid form
130 if (!$form->isSubmitted() || !$form->isValid()) {
131 //Render the view
132 return $this->render('@RapsysAir/application/add.html.twig', ['form' => $form->createView()]+$this->context);
133 }
134
135 //Get data
136 $data = $form->getData();
137
138 //Protect session fetching
139 try {
140 //Fetch session
141 $session = $this->doctrine->getRepository(Session::class)->findOneByLocationSlotDate($data['location'], $data['slot'], $data['date']);
142 //Catch no session case
143 } catch (NoResultException $e) {
144 //Create the session
145 $session = new Session($data['date'], $data['location'], $data['slot']);
146
147 //Get location
148 $location = $data['location']->getTitle();
149
150 //Get slot
151 $slot = $data['slot']->getTitle();
152
153 //Get premium
154 //XXX: premium is stored only for Afternoon and Evening
155 $premium = $session->isPremium();
156
157 //Set default length at 6h
158 //XXX: date part will be truncated on save
159 $session->setLength(new \DateTime('06:00:00'));
160
161 //Check if admin
162 if ($this->checker->isGranted('ROLE_ADMIN')) {
163 //Check if morning
164 if ($slot == 'Morning') {
165 //Set begin at 9h
166 $session->setBegin(new \DateTime('10:00:00'));
167
168 //Set length at 5h
169 $session->setLength(new \DateTime('05:00:00'));
170 //Check if afternoon
171 } elseif ($slot == 'Afternoon') {
172 //Set begin at 18h
173 $session->setBegin(new \DateTime('15:00:00'));
174
175 //Set length at 5h
176 $session->setLength(new \DateTime('04:00:00'));
177
178 //Check if next day is premium
179 if ($premium) {
180 //Set length at 11h
181 $session->setLength(new \DateTime('11:00:00'));
182 }
183 //Check if evening
184 } elseif ($slot == 'Evening') {
185 //Set begin at 19h00
186 $session->setBegin(new \DateTime('19:00:00'));
187
188 //Set length at 5h
189 $session->setLength(new \DateTime('06:00:00'));
190
191 //Check if next day is premium
192 if ($premium) {
193 //Set length at 7h
194 $session->setLength(new \DateTime('07:00:00'));
195 }
196 //Check if after
197 } else {
198 //Set begin at 1h
199 $session->setBegin(new \DateTime('01:00:00'));
200
201 //Set length at 4h
202 $session->setLength(new \DateTime('04:00:00'));
203
204 //Check if next day is premium
205 if ($premium) {
206 //Set begin at 2h
207 $session->setBegin(new \DateTime('02:00:00'));
208
209 //Set length at 3h
210 $session->setLength(new \DateTime('03:00:00'));
211 }
212 }
213 //Tino-Rossi garden => 14h -> 19h | 19h -> 01/02h
214 } elseif (in_array($location, ['Tino-Rossi garden']) && in_array($slot, ['Afternoon', 'Evening', 'After'])) {
215 //Check if afternoon
216 if ($slot == 'Afternoon') {
217 //Set begin at 14h
218 $session->setBegin(new \DateTime('14:00:00'));
219
220 //Set length at 5h
221 $session->setLength(new \DateTime('05:00:00'));
222 //Check if evening
223 } elseif ($slot == 'Evening') {
224 //Set begin at 19h
225 $session->setBegin(new \DateTime('19:00:00'));
226
227 //Check if next day is premium
228 if ($premium) {
229 //Set length at 7h
230 $session->setLength(new \DateTime('07:00:00'));
231 }
232 //Check if after
233 } else {
234 //Set begin at 1h
235 $session->setBegin(new \DateTime('01:00:00'));
236
237 //Set length at 4h
238 $session->setLength(new \DateTime('04:00:00'));
239
240 //Check if next day is premium
241 if ($premium) {
242 //Set begin at 2h
243 $session->setBegin(new \DateTime('02:00:00'));
244
245 //Set length at 3h
246 $session->setLength(new \DateTime('03:00:00'));
247 }
248 }
249 //Garnier opera => 21h -> 01/02h
250 } elseif ($location == 'Garnier opera' && in_array($slot, ['Evening', 'After'])) {
251 //Check if evening
252 if ($slot == 'Evening') {
253 //Set begin at 21h
254 $session->setBegin(new \DateTime('21:00:00'));
255
256 //Set length at 5h
257 $session->setLength(new \DateTime('05:00:00'));
258
259 //Check if next day is premium
260 if ($premium) {
261 //Set length at 6h
262 $session->setLength(new \DateTime('06:00:00'));
263 }
264 //Check if after
265 } else {
266 //Set begin at 1h
267 $session->setBegin(new \DateTime('01:00:00'));
268
269 //Set length at 4h
270 $session->setLength(new \DateTime('04:00:00'));
271
272 //Check if next day is premium
273 if ($premium) {
274 //Set begin at 2h
275 $session->setBegin(new \DateTime('02:00:00'));
276
277 //Set length at 3h
278 $session->setLength(new \DateTime('03:00:00'));
279 }
280 }
281 //Trocadero esplanade|Tokyo palace|Swan island|Saint-Honore market|Orsay museum => 19h -> 01/02h
282 } elseif (in_array($location, ['Trocadero esplanade', 'Tokyo palace', 'Swan island', 'Saint-Honore market', 'Orsay museum']) && in_array($slot, ['Evening', 'After'])) {
283 //Check if evening
284 if ($slot == 'Evening') {
285 //Set begin at 19h
286 $session->setBegin(new \DateTime('19:00:00'));
287
288 //Check if next day is premium
289 if ($premium) {
290 //Set length at 7h
291 $session->setLength(new \DateTime('07:00:00'));
292 }
293 //Check if after
294 } else {
295 //Set begin at 1h
296 $session->setBegin(new \DateTime('01:00:00'));
297
298 //Set length at 4h
299 $session->setLength(new \DateTime('04:00:00'));
300
301 //Check if next day is premium
302 if ($premium) {
303 //Set begin at 2h
304 $session->setBegin(new \DateTime('02:00:00'));
305
306 //Set length at 3h
307 $session->setLength(new \DateTime('03:00:00'));
308 }
309 }
310 //Drawings' garden (Villette) => 14h -> 19h
311 } elseif ($location == 'Drawings\' garden' && $slot == 'Afternoon') {
312 //Set begin at 14h
313 $session->setBegin(new \DateTime('14:00:00'));
314
315 //Set length at 5h
316 $session->setLength(new \DateTime('05:00:00'));
317 //Colette place => 14h -> 21h
318 //TODO: add check here that it's a millegaux account ?
319 } elseif ($location == 'Colette place' && $slot == 'Afternoon') {
320 //Set begin at 14h
321 $session->setBegin(new \DateTime('14:00:00'));
322
323 //Set length at 7h
324 $session->setLength(new \DateTime('07:00:00'));
325 //Orleans gallery => 14h -> 18h
326 } elseif ($location == 'Orleans gallery' && $slot == 'Afternoon') {
327 //Set begin at 14h
328 $session->setBegin(new \DateTime('14:00:00'));
329
330 //Set length at 4h
331 $session->setLength(new \DateTime('04:00:00'));
332 //Monde garden => 14h -> 19h
333 //TODO: add check here that it's a raphael account ?
334 } elseif ($location == 'Monde garden' && $slot == 'Afternoon') {
335 //Set begin at 14h
336 $session->setBegin(new \DateTime('14:00:00'));
337
338 //Set length at 4h
339 $session->setLength(new \DateTime('05:00:00'));
340 //Combination not supported
341 //TODO: add Madeleine place|Bastille place|Vendome place ?
342 } else {
343 //Add error in flash message
344 $this->addFlash('error', $this->translator->trans('Session on %date% %location% %slot% not yet supported', ['%location%' => $this->translator->trans('at '.$data['location']), '%slot%' => $this->translator->trans('the '.strtolower(strval($data['slot']))), '%date%' => $data['date']->format('Y-m-d')]));
345
346 //Render the view
347 return $this->render('@RapsysAir/application/add.html.twig', ['form' => $form->createView()]+$this->context);
348 }
349
350 //Check if admin
351 if (!$this->checker->isGranted('ROLE_ADMIN') && $session->getStart() < new \DateTime('00:00:00')) {
352 //Add error in flash message
353 $this->addFlash('error', $this->translator->trans('Session in the past on %date% %location% %slot% not yet supported', ['%location%' => $this->translator->trans('at '.$data['location']), '%slot%' => $this->translator->trans('the '.strtolower(strval($data['slot']))), '%date%' => $data['date']->format('Y-m-d')]));
354
355 //Render the view
356 return $this->render('@RapsysAir/application/add.html.twig', ['form' => $form->createView()]+$this->context);
357 }
358
359 //Queue session save
360 $this->manager->persist($session);
361
362 //Flush to get the ids
363 #$this->manager->flush();
364
365 $this->addFlash('notice', $this->translator->trans('Session on %date% %location% %slot% created', ['%location%' => $this->translator->trans('at '.$data['location']), '%slot%' => $this->translator->trans('the '.strtolower(strval($data['slot']))), '%date%' => $data['date']->format('Y-m-d')]));
366 }
367
368 //Set user
369 $user = $this->security->getUser();
370
371 //Replace with requested user for admin
372 if ($this->checker->isGranted('ROLE_ADMIN') && !empty($data['user'])) {
373 $user = $this->doctrine->getRepository(User::class)->findOneById($data['user']);
374 }
375
376 //Protect application fetching
377 try {
378 //Retrieve application
379 $application = $this->doctrine->getRepository(Application::class)->findOneBySessionUser($session, $user);
380
381 //Add warning in flash message
382 $this->addFlash('warning', $this->translator->trans('Application on %date% %location% %slot% already exists', ['%location%' => $this->translator->trans('at '.$data['location']), '%slot%' => $this->translator->trans('the '.strtolower(strval($data['slot']))), '%date%' => $data['date']->format('Y-m-d')]));
383 //Catch no application and session without identifier (not persisted&flushed) cases
384 } catch (NoResultException|ORMInvalidArgumentException $e) {
385 //Create the application
386 $application = new Application();
387 $application->setDance($data['dance']);
388 $application->setSession($session);
389 $application->setUser($user);
390
391 //Refresh session updated field
392 $session->setUpdated(new \DateTime('now'));
393
394 //Queue session save
395 $this->manager->persist($session);
396
397 //Queue application save
398 $this->manager->persist($application);
399
400 //Flush to get the ids
401 $this->manager->flush();
402
403 //Add notice in flash message
404 $this->addFlash('notice', $this->translator->trans('Application on %date% %location% %slot% created', ['%location%' => $this->translator->trans('at '.$data['location']), '%slot%' => $this->translator->trans('the '.strtolower(strval($data['slot']))), '%date%' => $data['date']->format('Y-m-d')]));
405 }
406
407 //Extract and process referer
408 if ($referer = $request->headers->get('referer')) {
409 //Create referer request instance
410 $req = Request::create($referer);
411
412 //Get referer path
413 $path = $req->getPathInfo();
414
415 //Get referer query string
416 $query = $req->getQueryString();
417
418 //Remove script name
419 $path = str_replace($request->getScriptName(), '', $path);
420
421 //Try with referer path
422 try {
423 //Save old context
424 $oldContext = $this->router->getContext();
425
426 //Force clean context
427 //XXX: prevent MethodNotAllowedException because current context method is POST in onevendor/symfony/routing/Matcher/Dumper/CompiledUrlMatcherTrait.php+42
428 $this->router->setContext(new RequestContext());
429
430 //Retrieve route matching path
431 $route = $this->router->match($path);
432
433 //Reset context
434 $this->router->setContext($oldContext);
435
436 //Clear old context
437 unset($oldContext);
438
439 //Extract name
440 $name = $route['_route'];
441
442 //Remove route and controller from route defaults
443 unset($route['_route'], $route['_controller']);
444
445 //Check if session view route
446 if ($name == 'rapsysair_session_view' && !empty($route['id'])) {
447 //Replace id
448 $route['id'] = $session->getId();
449 //Other routes
450 } else {
451 //Set session
452 $route['session'] = $session->getId();
453 }
454
455 //Generate url
456 return $this->redirectToRoute($name, $route);
457 //No route matched
458 } catch (MethodNotAllowedException|ResourceNotFoundException $e) {
459 //Unset referer to fallback to default route
460 unset($referer);
461 }
462 }
463
464 //Redirect to cleanup the form
465 return $this->redirectToRoute('rapsysair', ['session' => $session->getId()]);
466 }
467 }