]> Raphaƫl G. Git Repositories - airbundle/blob - Controller/ApplicationController.php
Switch to new header system
[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:00:00'));
130
131 //Set length at 5h
132 $session->setLength(new \DateTime('05:00: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 //Combination not supported
281 } else {
282 //Add error in flash message
283 $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')]));
284
285 //Set section
286 $section = $this->translator->trans('Application add');
287
288 //Set title
289 $title = $this->translator->trans($this->config['site']['title']).' - '.$section;
290
291 //Render the view
292 return $this->render('@RapsysAir/application/add.html.twig', ['title' => $title, 'section' => $section, 'form' => $form->createView()]+$this->context);
293 }
294
295 //Check if admin
296 if (!$this->isGranted('ROLE_ADMIN') && $session->getStart() < new \DateTime('00:00:00')) {
297 //Add error in flash message
298 $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')]));
299
300 //Set section
301 $section = $this->translator->trans('Application add');
302
303 //Set title
304 $title = $this->translator->trans($this->config['site']['title']).' - '.$section;
305
306 //Render the view
307 return $this->render('@RapsysAir/application/add.html.twig', ['title' => $title, 'section' => $section, 'form' => $form->createView()]+$this->context);
308 }
309
310 //Queue session save
311 $manager->persist($session);
312
313 //Flush to get the ids
314 #$manager->flush();
315
316 $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')]));
317 }
318
319 //Set user
320 $user = $this->getUser();
321
322 //Replace with requested user for admin
323 if ($this->isGranted('ROLE_ADMIN') && !empty($data['user'])) {
324 $user = $this->getDoctrine()->getRepository(User::class)->findOneById($data['user']);
325 }
326
327 //Protect application fetching
328 try {
329 //Retrieve application
330 $application = $doctrine->getRepository(Application::class)->findOneBySessionUser($session, $user);
331
332 //Add warning in flash message
333 $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')]));
334 //Catch no application and session without identifier (not persisted&flushed) cases
335 } catch (\Doctrine\ORM\NoResultException|\Doctrine\ORM\ORMInvalidArgumentException $e) {
336 //Create the application
337 $application = new Application();
338 $application->setSession($session);
339 $application->setUser($user);
340 $application->setCreated(new \DateTime('now'));
341 $application->setUpdated(new \DateTime('now'));
342
343 //Refresh session updated field
344 $session->setUpdated(new \DateTime('now'));
345
346 //Queue session save
347 $manager->persist($session);
348
349 //Queue application save
350 $manager->persist($application);
351
352 //Flush to get the ids
353 $manager->flush();
354
355 //Add notice in flash message
356 $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')]));
357 }
358
359 //Extract and process referer
360 if ($referer = $request->headers->get('referer')) {
361 //Create referer request instance
362 $req = Request::create($referer);
363
364 //Get referer path
365 $path = $req->getPathInfo();
366
367 //Get referer query string
368 $query = $req->getQueryString();
369
370 //Remove script name
371 $path = str_replace($request->getScriptName(), '', $path);
372
373 //Try with referer path
374 try {
375 //Save old context
376 $oldContext = $this->router->getContext();
377
378 //Force clean context
379 //XXX: prevent MethodNotAllowedException because current context method is POST in onevendor/symfony/routing/Matcher/Dumper/CompiledUrlMatcherTrait.php+42
380 $this->router->setContext(new RequestContext());
381
382 //Retrieve route matching path
383 $route = $this->router->match($path);
384
385 //Reset context
386 $this->router->setContext($oldContext);
387
388 //Clear old context
389 unset($oldContext);
390
391 //Extract name
392 $name = $route['_route'];
393
394 //Remove route and controller from route defaults
395 unset($route['_route'], $route['_controller']);
396
397 //Check if session view route
398 if ($name == 'rapsys_air_session_view' && !empty($route['id'])) {
399 //Replace id
400 $route['id'] = $session->getId();
401 //Other routes
402 } else {
403 //Set session
404 $route['session'] = $session->getId();
405 }
406
407 //Generate url
408 return $this->redirectToRoute($name, $route);
409 //No route matched
410 } catch(MethodNotAllowedException|ResourceNotFoundException $e) {
411 //Unset referer to fallback to default route
412 unset($referer);
413 }
414 }
415
416 //Redirect to cleanup the form
417 return $this->redirectToRoute('rapsys_air', ['session' => $session->getId()]);
418 }
419
420 /**
421 * Compute eastern for selected year
422 *
423 * @param int $year The eastern year
424 *
425 * @return DateTime The eastern date
426 */
427 function getEastern($year) {
428 //Set static
429 static $data = null;
430 //Check if already computed
431 if (isset($data[$year])) {
432 //Return computed eastern
433 return $data[$year];
434 //Check if data is null
435 } elseif (is_null($data)) {
436 //Init data array
437 $data = [];
438 }
439 $d = (19 * ($year % 19) + 24) % 30;
440 $e = (2 * ($year % 4) + 4 * ($year % 7) + 6 * $d + 5) % 7;
441
442 $day = 22 + $d + $e;
443 $month = 3;
444
445 if ($day > 31) {
446 $day = $d + $e - 9;
447 $month = 4;
448 } elseif ($d == 29 && $e == 6) {
449 $day = 10;
450 $month = 4;
451 } elseif ($d == 28 && $e == 6) {
452 $day = 18;
453 $month = 4;
454 }
455
456 //Store eastern in data
457 return ($data[$year] = new \DateTime(sprintf('%04d-%02d-%02d', $year, $month, $day)));
458 }
459
460 /**
461 * Check if date is a premium day
462 *
463 * @desc Consider as premium a day off
464 *
465 * @param DateTime $date The date to check
466 * @return bool Whether the date is off or not
467 */
468 function isPremium($date) {
469 //Get day number
470 $w = $date->format('w');
471
472 //Check if weekend day
473 if ($w == 0 || $w == 6) {
474 //Date is weekend day
475 return true;
476 }
477
478 //Get date day
479 $d = $date->format('d');
480
481 //Get date month
482 $m = $date->format('m');
483
484 //Check if fixed holiday
485 if (
486 //Check if 1st january
487 ($d == 1 && $m == 1) ||
488 //Check if 1st may
489 ($d == 1 && $m == 5) ||
490 //Check if 8st may
491 ($d == 8 && $m == 5) ||
492 //Check if 14st july
493 ($d == 14 && $m == 7) ||
494 //Check if 15st august
495 ($d == 15 && $m == 8) ||
496 //Check if 1st november
497 ($d == 1 && $m == 11) ||
498 //Check if 11st november
499 ($d == 11 && $m == 11) ||
500 //Check if 25st december
501 ($d == 25 && $m == 12)
502 ) {
503 //Date is a fixed holiday
504 return true;
505 }
506
507 //Get eastern
508 $eastern = $this->getEastern($date->format('Y'));
509
510 //Check dynamic holidays
511 if (
512 (clone $eastern)->add(new \DateInterval('P1D')) == $date ||
513 (clone $eastern)->add(new \DateInterval('P39D')) == $date ||
514 (clone $eastern)->add(new \DateInterval('P50D')) == $date
515 ) {
516 //Date is a dynamic holiday
517 return true;
518 }
519
520 //Date is not a holiday and week day
521 return false;
522 }
523 }