]> Raphaƫl G. Git Repositories - airbundle/blob - Controller/ApplicationController.php
Prevent rainfall detection when provider change rain rank
[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 14h
129 $session->setBegin(new \DateTime('14:30:00'));
130
131 //Set length at 5h
132 $session->setLength(new \DateTime('04:30:00'));
133 //Check if evening
134 } elseif ($slot == 'Evening') {
135 //Set begin at 19h
136 $session->setBegin(new \DateTime('19:00: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 //Check if after
144 } else {
145 //Set begin at 1h
146 $session->setBegin(new \DateTime('01:00:00'));
147
148 //Set length at 4h
149 $session->setLength(new \DateTime('04:00:00'));
150
151 //Check if next day is premium
152 if ($premium) {
153 //Set begin at 2h
154 $session->setBegin(new \DateTime('02:00:00'));
155
156 //Set length at 3h
157 $session->setLength(new \DateTime('03:00:00'));
158 }
159 }
160 //Docks => 14h -> 19h | 19h -> 01/02h
161 //XXX: remove Garnier from here to switch back to 21h
162 } elseif (in_array($short, ['Docks', 'Garnier']) && in_array($slot, ['Afternoon', 'Evening', 'After'])) {
163 //Check if afternoon
164 if ($slot == 'Afternoon') {
165 //Set begin at 14h
166 $session->setBegin(new \DateTime('14:00:00'));
167
168 //Set length at 5h
169 $session->setLength(new \DateTime('05:00:00'));
170 //Check if evening
171 } elseif ($slot == 'Evening') {
172 //Set begin at 19h
173 $session->setBegin(new \DateTime('19:00:00'));
174
175 //Check if next day is premium
176 if ($premium) {
177 //Set length at 7h
178 $session->setLength(new \DateTime('07:00:00'));
179 }
180 //Check if after
181 } else {
182 //Set begin at 1h
183 $session->setBegin(new \DateTime('01:00:00'));
184
185 //Set length at 4h
186 $session->setLength(new \DateTime('04:00:00'));
187
188 //Check if next day is premium
189 if ($premium) {
190 //Set begin at 2h
191 $session->setBegin(new \DateTime('02:00:00'));
192
193 //Set length at 3h
194 $session->setLength(new \DateTime('03:00:00'));
195 }
196 }
197 //Garnier => 21h -> 01/02h
198 } elseif ($short == 'Garnier' && in_array($slot, ['Evening', 'After'])) {
199 //Check if evening
200 if ($slot == 'Evening') {
201 //Set begin at 21h
202 $session->setBegin(new \DateTime('21:00:00'));
203
204 //Set length at 5h
205 $session->setLength(new \DateTime('05:00:00'));
206
207 //Check if next day is premium
208 if ($premium) {
209 //Set length at 6h
210 $session->setLength(new \DateTime('06:00:00'));
211 }
212 //Check if after
213 } else {
214 //Set begin at 1h
215 $session->setBegin(new \DateTime('01:00:00'));
216
217 //Set length at 4h
218 $session->setLength(new \DateTime('04:00:00'));
219
220 //Check if next day is premium
221 if ($premium) {
222 //Set begin at 2h
223 $session->setBegin(new \DateTime('02:00:00'));
224
225 //Set length at 3h
226 $session->setLength(new \DateTime('03:00:00'));
227 }
228 }
229 //Trocadero|Tokyo|Swan|Honore|Orsay => 19h -> 01/02h
230 } elseif (in_array($short, ['Trocadero', 'Tokyo', 'Swan', 'Honore', 'Orsay']) && in_array($slot, ['Evening', 'After'])) {
231 //Check if evening
232 if ($slot == 'Evening') {
233 //Set begin at 19h
234 $session->setBegin(new \DateTime('19:00:00'));
235
236 //Check if next day is premium
237 if ($premium) {
238 //Set length at 7h
239 $session->setLength(new \DateTime('07:00:00'));
240 }
241 //Check if after
242 } else {
243 //Set begin at 1h
244 $session->setBegin(new \DateTime('01:00:00'));
245
246 //Set length at 4h
247 $session->setLength(new \DateTime('04:00:00'));
248
249 //Check if next day is premium
250 if ($premium) {
251 //Set begin at 2h
252 $session->setBegin(new \DateTime('02:00:00'));
253
254 //Set length at 3h
255 $session->setLength(new \DateTime('03:00:00'));
256 }
257 }
258 //La Villette => 14h -> 19h
259 } elseif ($short == 'Villette' && $slot == 'Afternoon') {
260 //Set begin at 14h
261 $session->setBegin(new \DateTime('14:00:00'));
262
263 //Set length at 5h
264 $session->setLength(new \DateTime('05:00:00'));
265 //Place Colette => 14h -> 21h
266 //TODO: add check here that it's a millegaux account ?
267 } elseif ($short == 'Colette' && $slot == 'Afternoon') {
268 //Set begin at 14h
269 $session->setBegin(new \DateTime('14:00:00'));
270
271 //Set length at 7h
272 $session->setLength(new \DateTime('07:00:00'));
273 //Galerie d'OrlƩans => 14h -> 18h
274 } elseif ($short == 'Orleans' && $slot == 'Afternoon') {
275 //Set begin at 14h
276 $session->setBegin(new \DateTime('14:00:00'));
277
278 //Set length at 4h
279 $session->setLength(new \DateTime('04:00:00'));
280 //Jardin du Monde => 14h -> 15h
281 } elseif ($short == 'Monde' && $slot == 'Morning') {
282 //Set begin at 14h
283 $session->setBegin(new \DateTime('14:00:00'));
284
285 //Set length at 4h
286 $session->setLength(new \DateTime('01:00:00'));
287 //Combination not supported
288 } else {
289 //Add error in flash message
290 $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')]));
291
292 //Set section
293 $section = $this->translator->trans('Application add');
294
295 //Set title
296 $title = $this->translator->trans($this->config['site']['title']).' - '.$section;
297
298 //Render the view
299 return $this->render('@RapsysAir/application/add.html.twig', ['title' => $title, 'section' => $section, 'form' => $form->createView()]+$this->context);
300 }
301
302 //Check if admin
303 if (!$this->isGranted('ROLE_ADMIN') && $session->getStart() < new \DateTime('00:00:00')) {
304 //Add error in flash message
305 $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')]));
306
307 //Set section
308 $section = $this->translator->trans('Application add');
309
310 //Set title
311 $title = $this->translator->trans($this->config['site']['title']).' - '.$section;
312
313 //Render the view
314 return $this->render('@RapsysAir/application/add.html.twig', ['title' => $title, 'section' => $section, 'form' => $form->createView()]+$this->context);
315 }
316
317 //Queue session save
318 $manager->persist($session);
319
320 //Flush to get the ids
321 #$manager->flush();
322
323 $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')]));
324 }
325
326 //Set user
327 $user = $this->getUser();
328
329 //Replace with requested user for admin
330 if ($this->isGranted('ROLE_ADMIN') && !empty($data['user'])) {
331 $user = $this->getDoctrine()->getRepository(User::class)->findOneById($data['user']);
332 }
333
334 //Protect application fetching
335 try {
336 //Retrieve application
337 $application = $doctrine->getRepository(Application::class)->findOneBySessionUser($session, $user);
338
339 //Add warning in flash message
340 $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')]));
341 //Catch no application and session without identifier (not persisted&flushed) cases
342 } catch (\Doctrine\ORM\NoResultException|\Doctrine\ORM\ORMInvalidArgumentException $e) {
343 //Create the application
344 $application = new Application();
345 $application->setSession($session);
346 $application->setUser($user);
347 $application->setCreated(new \DateTime('now'));
348 $application->setUpdated(new \DateTime('now'));
349
350 //Refresh session updated field
351 $session->setUpdated(new \DateTime('now'));
352
353 //Queue session save
354 $manager->persist($session);
355
356 //Queue application save
357 $manager->persist($application);
358
359 //Flush to get the ids
360 $manager->flush();
361
362 //Add notice in flash message
363 $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')]));
364 }
365
366 //Extract and process referer
367 if ($referer = $request->headers->get('referer')) {
368 //Create referer request instance
369 $req = Request::create($referer);
370
371 //Get referer path
372 $path = $req->getPathInfo();
373
374 //Get referer query string
375 $query = $req->getQueryString();
376
377 //Remove script name
378 $path = str_replace($request->getScriptName(), '', $path);
379
380 //Try with referer path
381 try {
382 //Save old context
383 $oldContext = $this->router->getContext();
384
385 //Force clean context
386 //XXX: prevent MethodNotAllowedException because current context method is POST in onevendor/symfony/routing/Matcher/Dumper/CompiledUrlMatcherTrait.php+42
387 $this->router->setContext(new RequestContext());
388
389 //Retrieve route matching path
390 $route = $this->router->match($path);
391
392 //Reset context
393 $this->router->setContext($oldContext);
394
395 //Clear old context
396 unset($oldContext);
397
398 //Extract name
399 $name = $route['_route'];
400
401 //Remove route and controller from route defaults
402 unset($route['_route'], $route['_controller']);
403
404 //Check if session view route
405 if ($name == 'rapsys_air_session_view' && !empty($route['id'])) {
406 //Replace id
407 $route['id'] = $session->getId();
408 //Other routes
409 } else {
410 //Set session
411 $route['session'] = $session->getId();
412 }
413
414 //Generate url
415 return $this->redirectToRoute($name, $route);
416 //No route matched
417 } catch(MethodNotAllowedException|ResourceNotFoundException $e) {
418 //Unset referer to fallback to default route
419 unset($referer);
420 }
421 }
422
423 //Redirect to cleanup the form
424 return $this->redirectToRoute('rapsys_air', ['session' => $session->getId()]);
425 }
426
427 /**
428 * Compute eastern for selected year
429 *
430 * @param int $year The eastern year
431 *
432 * @return DateTime The eastern date
433 */
434 function getEastern($year) {
435 //Set static
436 static $data = null;
437 //Check if already computed
438 if (isset($data[$year])) {
439 //Return computed eastern
440 return $data[$year];
441 //Check if data is null
442 } elseif (is_null($data)) {
443 //Init data array
444 $data = [];
445 }
446 $d = (19 * ($year % 19) + 24) % 30;
447 $e = (2 * ($year % 4) + 4 * ($year % 7) + 6 * $d + 5) % 7;
448
449 $day = 22 + $d + $e;
450 $month = 3;
451
452 if ($day > 31) {
453 $day = $d + $e - 9;
454 $month = 4;
455 } elseif ($d == 29 && $e == 6) {
456 $day = 10;
457 $month = 4;
458 } elseif ($d == 28 && $e == 6) {
459 $day = 18;
460 $month = 4;
461 }
462
463 //Store eastern in data
464 return ($data[$year] = new \DateTime(sprintf('%04d-%02d-%02d', $year, $month, $day)));
465 }
466
467 /**
468 * Check if date is a premium day
469 *
470 * @desc Consider as premium a day off
471 *
472 * @param DateTime $date The date to check
473 * @return bool Whether the date is off or not
474 */
475 function isPremium($date) {
476 //Get day number
477 $w = $date->format('w');
478
479 //Check if weekend day
480 if ($w == 0 || $w == 6) {
481 //Date is weekend day
482 return true;
483 }
484
485 //Get date day
486 $d = $date->format('d');
487
488 //Get date month
489 $m = $date->format('m');
490
491 //Check if fixed holiday
492 if (
493 //Check if 1st january
494 ($d == 1 && $m == 1) ||
495 //Check if 1st may
496 ($d == 1 && $m == 5) ||
497 //Check if 8st may
498 ($d == 8 && $m == 5) ||
499 //Check if 14st july
500 ($d == 14 && $m == 7) ||
501 //Check if 15st august
502 ($d == 15 && $m == 8) ||
503 //Check if 1st november
504 ($d == 1 && $m == 11) ||
505 //Check if 11st november
506 ($d == 11 && $m == 11) ||
507 //Check if 25st december
508 ($d == 25 && $m == 12)
509 ) {
510 //Date is a fixed holiday
511 return true;
512 }
513
514 //Get eastern
515 $eastern = $this->getEastern($date->format('Y'));
516
517 //Check dynamic holidays
518 if (
519 (clone $eastern)->add(new \DateInterval('P1D')) == $date ||
520 (clone $eastern)->add(new \DateInterval('P39D')) == $date ||
521 (clone $eastern)->add(new \DateInterval('P50D')) == $date
522 ) {
523 //Date is a dynamic holiday
524 return true;
525 }
526
527 //Date is not a holiday and week day
528 return false;
529 }
530 }