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