]> Raphaël G. Git Repositories - airbundle/blob - Controller/ApplicationController.php
Add air bundle env variables
[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 * @desc 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('rapsys_air_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();
146 $session->setLocation($data['location']);
147 $session->setDate($data['date']);
148 $session->setSlot($data['slot']);
149
150 //Get location
151 $location = $data['location']->getTitle();
152
153 //Get slot
154 $slot = $data['slot']->getTitle();
155
156 //Get premium
157 //XXX: premium is stored only for Afternoon and Evening
158 $premium = $session->isPremium();
159
160 //Set default length at 6h
161 //XXX: date part will be truncated on save
162 $session->setLength(new \DateTime('06:00:00'));
163
164 //Check if admin
165 if ($this->checker->isGranted('ROLE_ADMIN')) {
166 //Check if morning
167 if ($slot == 'Morning') {
168 //Set begin at 9h
169 $session->setBegin(new \DateTime('09:00:00'));
170
171 //Set length at 5h
172 $session->setLength(new \DateTime('05:00:00'));
173 //Check if afternoon
174 } elseif ($slot == 'Afternoon') {
175 //Set begin at 18h
176 $session->setBegin(new \DateTime('15:30:00'));
177
178 //Set length at 5h
179 $session->setLength(new \DateTime('05:30:00'));
180 //Check if evening
181 } elseif ($slot == 'Evening') {
182 //Set begin at 19h00
183 $session->setBegin(new \DateTime('19:30:00'));
184
185 //Set length at 5h
186 $session->setLength(new \DateTime('05:30:00'));
187
188 //Check if next day is premium
189 if ($premium) {
190 //Set length at 7h
191 $session->setLength(new \DateTime('06:30:00'));
192 }
193 //Check if after
194 } else {
195 //Set begin at 1h
196 $session->setBegin(new \DateTime('01:00:00'));
197
198 //Set length at 4h
199 $session->setLength(new \DateTime('04:00:00'));
200
201 //Check if next day is premium
202 if ($premium) {
203 //Set begin at 2h
204 $session->setBegin(new \DateTime('02:00:00'));
205
206 //Set length at 3h
207 $session->setLength(new \DateTime('03:00:00'));
208 }
209 }
210 //Tino-Rossi garden => 14h -> 19h | 19h -> 01/02h
211 } elseif (in_array($location, ['Tino-Rossi garden']) && in_array($slot, ['Afternoon', 'Evening', 'After'])) {
212 //Check if afternoon
213 if ($slot == 'Afternoon') {
214 //Set begin at 14h
215 $session->setBegin(new \DateTime('14:00:00'));
216
217 //Set length at 5h
218 $session->setLength(new \DateTime('05:00:00'));
219 //Check if evening
220 } elseif ($slot == 'Evening') {
221 //Set begin at 19h
222 $session->setBegin(new \DateTime('19:00:00'));
223
224 //Check if next day is premium
225 if ($premium) {
226 //Set length at 7h
227 $session->setLength(new \DateTime('07:00:00'));
228 }
229 //Check if after
230 } else {
231 //Set begin at 1h
232 $session->setBegin(new \DateTime('01:00:00'));
233
234 //Set length at 4h
235 $session->setLength(new \DateTime('04:00:00'));
236
237 //Check if next day is premium
238 if ($premium) {
239 //Set begin at 2h
240 $session->setBegin(new \DateTime('02:00:00'));
241
242 //Set length at 3h
243 $session->setLength(new \DateTime('03:00:00'));
244 }
245 }
246 //Garnier opera => 21h -> 01/02h
247 } elseif ($location == 'Garnier opera' && in_array($slot, ['Evening', 'After'])) {
248 //Check if evening
249 if ($slot == 'Evening') {
250 //Set begin at 21h
251 $session->setBegin(new \DateTime('21:00:00'));
252
253 //Set length at 5h
254 $session->setLength(new \DateTime('05:00:00'));
255
256 //Check if next day is premium
257 if ($premium) {
258 //Set length at 6h
259 $session->setLength(new \DateTime('06:00:00'));
260 }
261 //Check if after
262 } else {
263 //Set begin at 1h
264 $session->setBegin(new \DateTime('01:00:00'));
265
266 //Set length at 4h
267 $session->setLength(new \DateTime('04:00:00'));
268
269 //Check if next day is premium
270 if ($premium) {
271 //Set begin at 2h
272 $session->setBegin(new \DateTime('02:00:00'));
273
274 //Set length at 3h
275 $session->setLength(new \DateTime('03:00:00'));
276 }
277 }
278 //Trocadero esplanade|Tokyo palace|Swan island|Saint-Honore market|Orsay museum => 19h -> 01/02h
279 } elseif (in_array($location, ['Trocadero esplanade', 'Tokyo palace', 'Swan island', 'Saint-Honore market', 'Orsay museum']) && in_array($slot, ['Evening', 'After'])) {
280 //Check if evening
281 if ($slot == 'Evening') {
282 //Set begin at 19h
283 $session->setBegin(new \DateTime('19:00:00'));
284
285 //Check if next day is premium
286 if ($premium) {
287 //Set length at 7h
288 $session->setLength(new \DateTime('07:00:00'));
289 }
290 //Check if after
291 } else {
292 //Set begin at 1h
293 $session->setBegin(new \DateTime('01:00:00'));
294
295 //Set length at 4h
296 $session->setLength(new \DateTime('04:00:00'));
297
298 //Check if next day is premium
299 if ($premium) {
300 //Set begin at 2h
301 $session->setBegin(new \DateTime('02:00:00'));
302
303 //Set length at 3h
304 $session->setLength(new \DateTime('03:00:00'));
305 }
306 }
307 //Drawings' garden (Villette) => 14h -> 19h
308 } elseif ($location == 'Drawings\' garden' && $slot == 'Afternoon') {
309 //Set begin at 14h
310 $session->setBegin(new \DateTime('14:00:00'));
311
312 //Set length at 5h
313 $session->setLength(new \DateTime('05:00:00'));
314 //Colette place => 14h -> 21h
315 //TODO: add check here that it's a millegaux account ?
316 } elseif ($location == 'Colette place' && $slot == 'Afternoon') {
317 //Set begin at 14h
318 $session->setBegin(new \DateTime('14:00:00'));
319
320 //Set length at 7h
321 $session->setLength(new \DateTime('07:00:00'));
322 //Orleans gallery => 14h -> 18h
323 } elseif ($location == 'Orleans gallery' && $slot == 'Afternoon') {
324 //Set begin at 14h
325 $session->setBegin(new \DateTime('14:00:00'));
326
327 //Set length at 4h
328 $session->setLength(new \DateTime('04:00:00'));
329 //Monde garden => 14h -> 19h
330 //TODO: add check here that it's a raphael account ?
331 } elseif ($location == 'Monde garden' && $slot == 'Afternoon') {
332 //Set begin at 14h
333 $session->setBegin(new \DateTime('14:00:00'));
334
335 //Set length at 4h
336 $session->setLength(new \DateTime('05:00:00'));
337 //Combination not supported
338 //TODO: add Madeleine place|Bastille place|Vendome place ?
339 } else {
340 //Add error in flash message
341 $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')]));
342
343 //Render the view
344 return $this->render('@RapsysAir/application/add.html.twig', ['form' => $form->createView()]+$this->context);
345 }
346
347 //Check if admin
348 if (!$this->checker->isGranted('ROLE_ADMIN') && $session->getStart() < new \DateTime('00:00:00')) {
349 //Add error in flash message
350 $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')]));
351
352 //Render the view
353 return $this->render('@RapsysAir/application/add.html.twig', ['form' => $form->createView()]+$this->context);
354 }
355
356 //Queue session save
357 $this->manager->persist($session);
358
359 //Flush to get the ids
360 #$this->manager->flush();
361
362 $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')]));
363 }
364
365 //Set user
366 $user = $this->security->getUser();
367
368 //Replace with requested user for admin
369 if ($this->checker->isGranted('ROLE_ADMIN') && !empty($data['user'])) {
370 $user = $this->doctrine->getRepository(User::class)->findOneById($data['user']);
371 }
372
373 //Protect application fetching
374 try {
375 //Retrieve application
376 $application = $this->doctrine->getRepository(Application::class)->findOneBySessionUser($session, $user);
377
378 //Add warning in flash message
379 $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')]));
380 //Catch no application and session without identifier (not persisted&flushed) cases
381 } catch (NoResultException|ORMInvalidArgumentException $e) {
382 //Create the application
383 $application = new Application();
384 $application->setDance($data['dance']);
385 $application->setSession($session);
386 $application->setUser($user);
387
388 //Refresh session updated field
389 $session->setUpdated(new \DateTime('now'));
390
391 //Queue session save
392 $this->manager->persist($session);
393
394 //Queue application save
395 $this->manager->persist($application);
396
397 //Flush to get the ids
398 $this->manager->flush();
399
400 //Add notice in flash message
401 $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')]));
402 }
403
404 //Extract and process referer
405 if ($referer = $request->headers->get('referer')) {
406 //Create referer request instance
407 $req = Request::create($referer);
408
409 //Get referer path
410 $path = $req->getPathInfo();
411
412 //Get referer query string
413 $query = $req->getQueryString();
414
415 //Remove script name
416 $path = str_replace($request->getScriptName(), '', $path);
417
418 //Try with referer path
419 try {
420 //Save old context
421 $oldContext = $this->router->getContext();
422
423 //Force clean context
424 //XXX: prevent MethodNotAllowedException because current context method is POST in onevendor/symfony/routing/Matcher/Dumper/CompiledUrlMatcherTrait.php+42
425 $this->router->setContext(new RequestContext());
426
427 //Retrieve route matching path
428 $route = $this->router->match($path);
429
430 //Reset context
431 $this->router->setContext($oldContext);
432
433 //Clear old context
434 unset($oldContext);
435
436 //Extract name
437 $name = $route['_route'];
438
439 //Remove route and controller from route defaults
440 unset($route['_route'], $route['_controller']);
441
442 //Check if session view route
443 if ($name == 'rapsys_air_session_view' && !empty($route['id'])) {
444 //Replace id
445 $route['id'] = $session->getId();
446 //Other routes
447 } else {
448 //Set session
449 $route['session'] = $session->getId();
450 }
451
452 //Generate url
453 return $this->redirectToRoute($name, $route);
454 //No route matched
455 } catch (MethodNotAllowedException|ResourceNotFoundException $e) {
456 //Unset referer to fallback to default route
457 unset($referer);
458 }
459 }
460
461 //Redirect to cleanup the form
462 return $this->redirectToRoute('rapsys_air', ['session' => $session->getId()]);
463 }
464 }