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