]> Raphaƫl G. Git Repositories - airbundle/blob - Controller/ApplicationController.php
Switch to full locales
[airbundle] / Controller / ApplicationController.php
1 <?php
2
3 namespace Rapsys\AirBundle\Controller;
4
5 use Symfony\Component\HttpFoundation\Request;
6 use Symfony\Component\HttpFoundation\Response;
7 use Symfony\Component\Routing\RequestContext;
8 use Symfony\Component\Form\FormError;
9 use Symfony\Component\Routing\Exception\MethodNotAllowedException;
10 use Symfony\Component\Routing\Exception\ResourceNotFoundException;
11 use Rapsys\AirBundle\Entity\Slot;
12 use Rapsys\AirBundle\Entity\User;
13 use Rapsys\AirBundle\Entity\Session;
14 use Rapsys\AirBundle\Entity\Application;
15
16 class ApplicationController extends DefaultController {
17 /**
18 * Add application
19 *
20 * @desc Persist application and all required dependencies in database
21 *
22 * @param Request $request The request instance
23 *
24 * @return Response The rendered view or redirection
25 *
26 * @throws \RuntimeException When user has not at least guest role
27 */
28 public function add(Request $request) {
29 //Prevent non-guest to access here
30 $this->denyAccessUnlessGranted('ROLE_GUEST', null, $this->translator->trans('Unable to access this page without role %role%!', ['%role%' => $this->translator->trans('Guest')]));
31
32 //Create ApplicationType form
33 $form = $this->createForm('Rapsys\AirBundle\Form\ApplicationType', null, [
34 //Set the action
35 'action' => $this->generateUrl('rapsys_air_application_add'),
36 //Set the form attribute
37 #'attr' => [ 'class' => 'col' ],
38 //Set admin
39 'admin' => $this->isGranted('ROLE_ADMIN'),
40 //Set default user to current
41 'user' => $this->getUser()->getId(),
42 //Set default slot to evening
43 //XXX: default to Evening (3)
44 'slot' => $this->getDoctrine()->getRepository(Slot::class)->findOneById(3)
45 ]);
46
47 //Refill the fields in case of invalid form
48 $form->handleRequest($request);
49
50 //Handle invalid form
51 if (!$form->isSubmitted() || !$form->isValid()) {
52 //Set section
53 $section = $this->translator->trans('Application add');
54
55 //Set title
56 $title = $this->translator->trans($this->config['site']['title']).' - '.$section;
57
58 //Render the view
59 return $this->render('@RapsysAir/application/add.html.twig', ['title' => $title, 'section' => $section, 'form' => $form->createView()]+$this->context);
60 }
61
62 //Get doctrine
63 $doctrine = $this->getDoctrine();
64
65 //Get manager
66 $manager = $doctrine->getManager();
67
68 //Get data
69 $data = $form->getData();
70
71 //Protect session fetching
72 try {
73 //Fetch session
74 $session = $doctrine->getRepository(Session::class)->findOneByLocationSlotDate($data['location'], $data['slot'], $data['date']);
75 //Catch no session case
76 } catch (\Doctrine\ORM\NoResultException $e) {
77 //Create the session
78 $session = new Session();
79 $session->setLocation($data['location']);
80 $session->setDate($data['date']);
81 $session->setSlot($data['slot']);
82 $session->setCreated(new \DateTime('now'));
83 $session->setUpdated(new \DateTime('now'));
84
85 //Get short location
86 $short = $data['location']->getShort();
87
88 //Get slot
89 $slot = $data['slot']->getTitle();
90
91 //Set premium
92 $session->setPremium($premium = false);
93
94 //Check if slot is afternoon
95 //XXX: premium is stored only for Afternoon and Evening
96 if ($slot == 'Afternoon') {
97 //Compute premium
98 //XXX: a session is considered premium a day off
99 $session->setPremium($premium = $this->isPremium($data['date']));
100 //Check if slot is evening
101 //XXX: premium is stored only for Afternoon and Evening
102 } elseif ($slot == 'Evening') {
103 //Compute premium
104 //XXX: a session is considered premium the eve of a day off
105 $session->setPremium($premium = $this->isPremium((clone $data['date'])->add(new \DateInterval('P1D'))));
106 //Check if slot is after
107 } elseif ($slot == 'After') {
108 //Compute premium
109 //XXX: a session is considered premium the eve of a day off
110 $premium = $this->isPremium((clone $data['date'])->add(new \DateInterval('P1D')));
111 }
112
113 //Set default length at 6h
114 //XXX: date part will be truncated on save
115 $session->setLength(new \DateTime('06:00:00'));
116
117 //Check if admin
118 if ($this->isGranted('ROLE_ADMIN')) {
119 //Check if morning
120 if ($slot == 'Morning') {
121 //Set begin at 9h
122 $session->setBegin(new \DateTime('09:00:00'));
123
124 //Set length at 5h
125 $session->setLength(new \DateTime('05:00:00'));
126 //Check if afternoon
127 } elseif ($slot == 'Afternoon') {
128 //Set begin at 16h
129 $session->setBegin(new \DateTime('16:00:00'));
130
131 //Set length at 3h
132 $session->setLength(new \DateTime('03:00:00'));
133 //Check if evening
134 } elseif ($slot == 'Evening') {
135 //Set begin at 19h
136 $session->setBegin(new \DateTime('19:30:00'));
137
138 //Check if next day is premium
139 if ($premium) {
140 //Set length at 7h
141 $session->setLength(new \DateTime('07:00:00'));
142 }
143
144 //Set length at 4h
145 $session->setLength(new \DateTime('04:30:00'));
146 //Check if after
147 } else {
148 //Set begin at 1h
149 $session->setBegin(new \DateTime('01:00:00'));
150
151 //Set length at 4h
152 $session->setLength(new \DateTime('04:00:00'));
153
154 //Check if next day is premium
155 if ($premium) {
156 //Set begin at 2h
157 $session->setBegin(new \DateTime('02:00:00'));
158
159 //Set length at 3h
160 $session->setLength(new \DateTime('03:00:00'));
161 }
162 }
163 //Docks => 14h -> 19h | 19h -> 01/02h
164 //XXX: remove Garnier from here to switch back to 21h
165 } elseif (in_array($short, ['Docks', 'Garnier']) && in_array($slot, ['Afternoon', 'Evening', 'After'])) {
166 //Check if afternoon
167 if ($slot == 'Afternoon') {
168 //Set begin at 14h
169 $session->setBegin(new \DateTime('14:00:00'));
170
171 //Set length at 5h
172 $session->setLength(new \DateTime('05:00:00'));
173 //Check if evening
174 } elseif ($slot == 'Evening') {
175 //Set begin at 19h
176 $session->setBegin(new \DateTime('19:00:00'));
177
178 //Check if next day is premium
179 if ($premium) {
180 //Set length at 7h
181 $session->setLength(new \DateTime('07:00:00'));
182 }
183 //Check if after
184 } else {
185 //Set begin at 1h
186 $session->setBegin(new \DateTime('01:00:00'));
187
188 //Set length at 4h
189 $session->setLength(new \DateTime('04:00:00'));
190
191 //Check if next day is premium
192 if ($premium) {
193 //Set begin at 2h
194 $session->setBegin(new \DateTime('02:00:00'));
195
196 //Set length at 3h
197 $session->setLength(new \DateTime('03:00:00'));
198 }
199 }
200 //Garnier => 21h -> 01/02h
201 } elseif ($short == 'Garnier' && in_array($slot, ['Evening', 'After'])) {
202 //Check if evening
203 if ($slot == 'Evening') {
204 //Set begin at 21h
205 $session->setBegin(new \DateTime('21:00:00'));
206
207 //Set length at 5h
208 $session->setLength(new \DateTime('05:00:00'));
209
210 //Check if next day is premium
211 if ($premium) {
212 //Set length at 6h
213 $session->setLength(new \DateTime('06:00:00'));
214 }
215 //Check if after
216 } else {
217 //Set begin at 1h
218 $session->setBegin(new \DateTime('01:00:00'));
219
220 //Set length at 4h
221 $session->setLength(new \DateTime('04:00:00'));
222
223 //Check if next day is premium
224 if ($premium) {
225 //Set begin at 2h
226 $session->setBegin(new \DateTime('02:00:00'));
227
228 //Set length at 3h
229 $session->setLength(new \DateTime('03:00:00'));
230 }
231 }
232 //Trocadero|Tokyo|Swan|Honore|Orsay => 19h -> 01/02h
233 } elseif (in_array($short, ['Trocadero', 'Tokyo', 'Swan', 'Honore', 'Orsay']) && in_array($slot, ['Evening', 'After'])) {
234 //Check if evening
235 if ($slot == 'Evening') {
236 //Set begin at 19h
237 $session->setBegin(new \DateTime('19:00:00'));
238
239 //Check if next day is premium
240 if ($premium) {
241 //Set length at 7h
242 $session->setLength(new \DateTime('07:00:00'));
243 }
244 //Check if after
245 } else {
246 //Set begin at 1h
247 $session->setBegin(new \DateTime('01:00:00'));
248
249 //Set length at 4h
250 $session->setLength(new \DateTime('04:00:00'));
251
252 //Check if next day is premium
253 if ($premium) {
254 //Set begin at 2h
255 $session->setBegin(new \DateTime('02:00:00'));
256
257 //Set length at 3h
258 $session->setLength(new \DateTime('03:00:00'));
259 }
260 }
261 //La Villette => 14h -> 19h
262 } elseif ($short == 'Villette' && $slot == 'Afternoon') {
263 //Set begin at 14h
264 $session->setBegin(new \DateTime('14:00:00'));
265
266 //Set length at 5h
267 $session->setLength(new \DateTime('05:00:00'));
268 //Place Colette => 14h -> 21h
269 //TODO: add check here that it's a millegaux account ?
270 } elseif ($short == 'Colette' && $slot == 'Afternoon') {
271 //Set begin at 14h
272 $session->setBegin(new \DateTime('14:00:00'));
273
274 //Set length at 7h
275 $session->setLength(new \DateTime('07:00:00'));
276 //Galerie d'OrlƩans => 14h -> 18h
277 } elseif ($short == 'Orleans' && $slot == 'Afternoon') {
278 //Set begin at 14h
279 $session->setBegin(new \DateTime('14:00:00'));
280
281 //Set length at 4h
282 $session->setLength(new \DateTime('04:00:00'));
283 //Jardin du Monde => 14h -> 15h
284 } elseif ($short == 'Monde' && $slot == 'Morning') {
285 //Set begin at 14h
286 $session->setBegin(new \DateTime('14:00:00'));
287
288 //Set length at 4h
289 $session->setLength(new \DateTime('01:00:00'));
290 //Combination not supported
291 } else {
292 //Add error in flash message
293 $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($data['slot'])), '%date%' => $data['date']->format('Y-m-d')]));
294
295 //Set section
296 $section = $this->translator->trans('Application add');
297
298 //Set title
299 $title = $this->translator->trans($this->config['site']['title']).' - '.$section;
300
301 //Render the view
302 return $this->render('@RapsysAir/application/add.html.twig', ['title' => $title, 'section' => $section, 'form' => $form->createView()]+$this->context);
303 }
304
305 //Check if admin
306 if (!$this->isGranted('ROLE_ADMIN') && $session->getStart() < new \DateTime('00:00:00')) {
307 //Add error in flash message
308 $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($data['slot'])), '%date%' => $data['date']->format('Y-m-d')]));
309
310 //Set section
311 $section = $this->translator->trans('Application add');
312
313 //Set title
314 $title = $this->translator->trans($this->config['site']['title']).' - '.$section;
315
316 //Render the view
317 return $this->render('@RapsysAir/application/add.html.twig', ['title' => $title, 'section' => $section, 'form' => $form->createView()]+$this->context);
318 }
319
320 //Queue session save
321 $manager->persist($session);
322
323 //Flush to get the ids
324 #$manager->flush();
325
326 $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($data['slot'])), '%date%' => $data['date']->format('Y-m-d')]));
327 }
328
329 //Set user
330 $user = $this->getUser();
331
332 //Replace with requested user for admin
333 if ($this->isGranted('ROLE_ADMIN') && !empty($data['user'])) {
334 $user = $this->getDoctrine()->getRepository(User::class)->findOneById($data['user']);
335 }
336
337 //Protect application fetching
338 try {
339 //Retrieve application
340 $application = $doctrine->getRepository(Application::class)->findOneBySessionUser($session, $user);
341
342 //Add warning in flash message
343 $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($data['slot'])), '%date%' => $data['date']->format('Y-m-d')]));
344 //Catch no application and session without identifier (not persisted&flushed) cases
345 } catch (\Doctrine\ORM\NoResultException|\Doctrine\ORM\ORMInvalidArgumentException $e) {
346 //Create the application
347 $application = new Application();
348 $application->setSession($session);
349 $application->setUser($user);
350 $application->setCreated(new \DateTime('now'));
351 $application->setUpdated(new \DateTime('now'));
352
353 //Refresh session updated field
354 $session->setUpdated(new \DateTime('now'));
355
356 //Queue session save
357 $manager->persist($session);
358
359 //Queue application save
360 $manager->persist($application);
361
362 //Flush to get the ids
363 $manager->flush();
364
365 //Add notice in flash message
366 $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($data['slot'])), '%date%' => $data['date']->format('Y-m-d')]));
367 }
368
369 //Extract and process referer
370 if ($referer = $request->headers->get('referer')) {
371 //Create referer request instance
372 $req = Request::create($referer);
373
374 //Get referer path
375 $path = $req->getPathInfo();
376
377 //Get referer query string
378 $query = $req->getQueryString();
379
380 //Remove script name
381 $path = str_replace($request->getScriptName(), '', $path);
382
383 //Try with referer path
384 try {
385 //Save old context
386 $oldContext = $this->router->getContext();
387
388 //Force clean context
389 //XXX: prevent MethodNotAllowedException because current context method is POST in onevendor/symfony/routing/Matcher/Dumper/CompiledUrlMatcherTrait.php+42
390 $this->router->setContext(new RequestContext());
391
392 //Retrieve route matching path
393 $route = $this->router->match($path);
394
395 //Reset context
396 $this->router->setContext($oldContext);
397
398 //Clear old context
399 unset($oldContext);
400
401 //Extract name
402 $name = $route['_route'];
403
404 //Remove route and controller from route defaults
405 unset($route['_route'], $route['_controller']);
406
407 //Check if session view route
408 if ($name == 'rapsys_air_session_view' && !empty($route['id'])) {
409 //Replace id
410 $route['id'] = $session->getId();
411 //Other routes
412 } else {
413 //Set session
414 $route['session'] = $session->getId();
415 }
416
417 //Generate url
418 return $this->redirectToRoute($name, $route);
419 //No route matched
420 } catch(MethodNotAllowedException|ResourceNotFoundException $e) {
421 //Unset referer to fallback to default route
422 unset($referer);
423 }
424 }
425
426 //Redirect to cleanup the form
427 return $this->redirectToRoute('rapsys_air', ['session' => $session->getId()]);
428 }
429
430 /**
431 * Compute eastern for selected year
432 *
433 * @param int $year The eastern year
434 *
435 * @return DateTime The eastern date
436 */
437 function getEastern($year) {
438 //Set static
439 static $data = null;
440 //Check if already computed
441 if (isset($data[$year])) {
442 //Return computed eastern
443 return $data[$year];
444 //Check if data is null
445 } elseif (is_null($data)) {
446 //Init data array
447 $data = [];
448 }
449 $d = (19 * ($year % 19) + 24) % 30;
450 $e = (2 * ($year % 4) + 4 * ($year % 7) + 6 * $d + 5) % 7;
451
452 $day = 22 + $d + $e;
453 $month = 3;
454
455 if ($day > 31) {
456 $day = $d + $e - 9;
457 $month = 4;
458 } elseif ($d == 29 && $e == 6) {
459 $day = 10;
460 $month = 4;
461 } elseif ($d == 28 && $e == 6) {
462 $day = 18;
463 $month = 4;
464 }
465
466 //Store eastern in data
467 return ($data[$year] = new \DateTime(sprintf('%04d-%02d-%02d', $year, $month, $day)));
468 }
469
470 /**
471 * Check if date is a premium day
472 *
473 * @desc Consider as premium a day off
474 *
475 * @param DateTime $date The date to check
476 * @return bool Whether the date is off or not
477 */
478 function isPremium($date) {
479 //Get day number
480 $w = $date->format('w');
481
482 //Check if weekend day
483 if ($w == 0 || $w == 6) {
484 //Date is weekend day
485 return true;
486 }
487
488 //Get date day
489 $d = $date->format('d');
490
491 //Get date month
492 $m = $date->format('m');
493
494 //Check if fixed holiday
495 if (
496 //Check if 1st january
497 ($d == 1 && $m == 1) ||
498 //Check if 1st may
499 ($d == 1 && $m == 5) ||
500 //Check if 8st may
501 ($d == 8 && $m == 5) ||
502 //Check if 14st july
503 ($d == 14 && $m == 7) ||
504 //Check if 15st august
505 ($d == 15 && $m == 8) ||
506 //Check if 1st november
507 ($d == 1 && $m == 11) ||
508 //Check if 11st november
509 ($d == 11 && $m == 11) ||
510 //Check if 25st december
511 ($d == 25 && $m == 12)
512 ) {
513 //Date is a fixed holiday
514 return true;
515 }
516
517 //Get eastern
518 $eastern = $this->getEastern($date->format('Y'));
519
520 //Check dynamic holidays
521 if (
522 (clone $eastern)->add(new \DateInterval('P1D')) == $date ||
523 (clone $eastern)->add(new \DateInterval('P39D')) == $date ||
524 (clone $eastern)->add(new \DateInterval('P50D')) == $date
525 ) {
526 //Date is a dynamic holiday
527 return true;
528 }
529
530 //Date is not a holiday and week day
531 return false;
532 }
533 }