]> Raphaël G. Git Repositories - airbundle/blob - Controller/ApplicationController.php
Add support for bundle named entity
[airbundle] / Controller / ApplicationController.php
1 <?php declare(strict_types=1);
2
3 /*
4 * This file is part of the Rapsys AirBundle package.
5 *
6 * (c) Raphaël Gertz <symfony@rapsys.eu>
7 *
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
10 */
11
12 namespace Rapsys\AirBundle\Controller;
13
14 use Doctrine\Bundle\DoctrineBundle\Registry;
15 use Doctrine\ORM\EntityManagerInterface;
16 use Doctrine\ORM\NoResultException;
17 use Doctrine\ORM\ORMInvalidArgumentException;
18 use Symfony\Component\Form\FormError;
19 use Symfony\Component\HttpFoundation\Request;
20 use Symfony\Component\HttpFoundation\Response;
21 use Symfony\Component\Routing\Exception\MethodNotAllowedException;
22 use Symfony\Component\Routing\Exception\ResourceNotFoundException;
23 use Symfony\Component\Routing\RequestContext;
24
25 use Rapsys\AirBundle\Entity\Application;
26 use Rapsys\AirBundle\Entity\Dance;
27 use Rapsys\AirBundle\Entity\Location;
28 use Rapsys\AirBundle\Entity\Session;
29 use Rapsys\AirBundle\Entity\Slot;
30 use Rapsys\AirBundle\Entity\User;
31
32 /**
33 * {@inheritdoc}
34 */
35 class ApplicationController extends AbstractController {
36 /**
37 * Add application
38 *
39 * @desc Persist application and all required dependencies in database
40 *
41 * @param Request $request The request instance
42 * @param Registry $manager The doctrine registry
43 * @param EntityManagerInterface $manager The doctrine entity manager
44 *
45 * @return Response The rendered view or redirection
46 *
47 * @throws \RuntimeException When user has not at least guest role
48 */
49 public function add(Request $request, Registry $doctrine, EntityManagerInterface $manager) {
50 //Prevent non-guest to access here
51 $this->denyAccessUnlessGranted('ROLE_GUEST', null, $this->translator->trans('Unable to access this page without role %role%!', ['%role%' => $this->translator->trans('Guest')]));
52
53 //Get favorites dances
54 $danceFavorites = $doctrine->getRepository(Dance::class)->findByUserId($this->getUser()->getId());
55
56 //Set dance default
57 $danceDefault = !empty($danceFavorites)?current($danceFavorites):null;
58
59
60 //Get favorites locations
61 $locationFavorites = $doctrine->getRepository(Location::class)->findByUserId($this->getUser()->getId());
62
63 //Set location default
64 $locationDefault = !empty($locationFavorites)?current($locationFavorites):null;
65
66 //With admin
67 if ($this->isGranted('ROLE_ADMIN')) {
68 //Get dances
69 $dances = $doctrine->getRepository(Dance::class)->findAll();
70
71 //Get locations
72 $locations = $doctrine->getRepository(Location::class)->findAll();
73 //Without admin
74 } else {
75 //Restrict to favorite dances
76 $dances = $danceFavorites;
77
78 //Reset favorites
79 $danceFavorites = [];
80
81 //Restrict to favorite locations
82 $locations = $locationFavorites;
83
84 //Reset favorites
85 $locationFavorites = [];
86 }
87
88 //Create ApplicationType form
89 $form = $this->createForm('Rapsys\AirBundle\Form\ApplicationType', null, [
90 //Set the action
91 'action' => $this->generateUrl('rapsys_air_application_add'),
92 //Set the form attribute
93 #'attr' => [ 'class' => 'col' ],
94 //Set dance choices
95 'dance_choices' => $dances,
96 //Set dance default
97 'dance_default' => $danceDefault,
98 //Set dance favorites
99 'dance_favorites' => $danceFavorites,
100 //Set location choices
101 'location_choices' => $locations,
102 //Set location default
103 'location_default' => $locationDefault,
104 //Set location favorites
105 'location_favorites' => $locationFavorites,
106 //With user
107 'user' => $this->isGranted('ROLE_ADMIN'),
108 //Set user choices
109 'user_choices' => $doctrine->getRepository(User::class)->findAllWithTranslatedGroupAndCivility($this->translator),
110 //Set default user to current
111 'user_default' => $this->getUser()->getId(),
112 //Set default slot to evening
113 //XXX: default to Evening (3)
114 'slot_default' => $doctrine->getRepository(Slot::class)->findOneByTitle('Evening')
115 ]);
116
117 //Refill the fields in case of invalid form
118 $form->handleRequest($request);
119
120 //Handle invalid form
121 if (!$form->isSubmitted() || !$form->isValid()) {
122 //Set title
123 $title = $this->translator->trans('Application add');
124
125 //Render the view
126 return $this->render('@RapsysAir/application/add.html.twig', ['title' => $title, 'form' => $form->createView()]+$this->context);
127 }
128
129 //Get data
130 $data = $form->getData();
131
132 //Protect session fetching
133 try {
134 //Fetch session
135 $session = $doctrine->getRepository(Session::class)->findOneByLocationSlotDate($data['location'], $data['slot'], $data['date']);
136 //Catch no session case
137 } catch (NoResultException $e) {
138 //Create the session
139 $session = new Session();
140 $session->setLocation($data['location']);
141 $session->setDate($data['date']);
142 $session->setSlot($data['slot']);
143
144 //Get location
145 $location = $data['location']->getTitle();
146
147 //Get slot
148 $slot = $data['slot']->getTitle();
149
150 //Get premium
151 //XXX: premium is stored only for Afternoon and Evening
152 $premium = $session->isPremium();
153
154 //Set default length at 6h
155 //XXX: date part will be truncated on save
156 $session->setLength(new \DateTime('06:00:00'));
157
158 //Check if admin
159 if ($this->isGranted('ROLE_ADMIN')) {
160 //Check if morning
161 if ($slot == 'Morning') {
162 //Set begin at 9h
163 $session->setBegin(new \DateTime('09:00:00'));
164
165 //Set length at 5h
166 $session->setLength(new \DateTime('05:00:00'));
167 //Check if afternoon
168 } elseif ($slot == 'Afternoon') {
169 //Set begin at 18h
170 $session->setBegin(new \DateTime('14:00:00'));
171
172 //Set length at 5h
173 $session->setLength(new \DateTime('05:00:00'));
174 //Check if evening
175 } elseif ($slot == 'Evening') {
176 //Set begin at 19h00
177 $session->setBegin(new \DateTime('19:00:00'));
178
179 //Check if next day is premium
180 if ($premium) {
181 //Set length at 7h
182 $session->setLength(new \DateTime('07:00:00'));
183 }
184 //Check if after
185 } else {
186 //Set begin at 1h
187 $session->setBegin(new \DateTime('01:00:00'));
188
189 //Set length at 4h
190 $session->setLength(new \DateTime('04:00:00'));
191
192 //Check if next day is premium
193 if ($premium) {
194 //Set begin at 2h
195 $session->setBegin(new \DateTime('02:00:00'));
196
197 //Set length at 3h
198 $session->setLength(new \DateTime('03:00:00'));
199 }
200 }
201 //Tino-Rossi garden => 14h -> 19h | 19h -> 01/02h
202 } elseif (in_array($location, ['Tino-Rossi garden']) && in_array($slot, ['Afternoon', 'Evening', 'After'])) {
203 //Check if afternoon
204 if ($slot == 'Afternoon') {
205 //Set begin at 14h
206 $session->setBegin(new \DateTime('14:00:00'));
207
208 //Set length at 5h
209 $session->setLength(new \DateTime('05:00:00'));
210 //Check if evening
211 } elseif ($slot == 'Evening') {
212 //Set begin at 19h
213 $session->setBegin(new \DateTime('19:00:00'));
214
215 //Check if next day is premium
216 if ($premium) {
217 //Set length at 7h
218 $session->setLength(new \DateTime('07:00:00'));
219 }
220 //Check if after
221 } else {
222 //Set begin at 1h
223 $session->setBegin(new \DateTime('01:00:00'));
224
225 //Set length at 4h
226 $session->setLength(new \DateTime('04:00:00'));
227
228 //Check if next day is premium
229 if ($premium) {
230 //Set begin at 2h
231 $session->setBegin(new \DateTime('02:00:00'));
232
233 //Set length at 3h
234 $session->setLength(new \DateTime('03:00:00'));
235 }
236 }
237 //Garnier opera => 21h -> 01/02h
238 } elseif ($location == 'Garnier opera' && in_array($slot, ['Evening', 'After'])) {
239 //Check if evening
240 if ($slot == 'Evening') {
241 //Set begin at 21h
242 $session->setBegin(new \DateTime('21:00:00'));
243
244 //Set length at 5h
245 $session->setLength(new \DateTime('05:00:00'));
246
247 //Check if next day is premium
248 if ($premium) {
249 //Set length at 6h
250 $session->setLength(new \DateTime('06:00:00'));
251 }
252 //Check if after
253 } else {
254 //Set begin at 1h
255 $session->setBegin(new \DateTime('01:00:00'));
256
257 //Set length at 4h
258 $session->setLength(new \DateTime('04:00:00'));
259
260 //Check if next day is premium
261 if ($premium) {
262 //Set begin at 2h
263 $session->setBegin(new \DateTime('02:00:00'));
264
265 //Set length at 3h
266 $session->setLength(new \DateTime('03:00:00'));
267 }
268 }
269 //Trocadero esplanade|Tokyo palace|Swan island|Saint-Honore market|Orsay museum => 19h -> 01/02h
270 } elseif (in_array($location, ['Trocadero esplanade', 'Tokyo palace', 'Swan island', 'Saint-Honore market', 'Orsay museum']) && in_array($slot, ['Evening', 'After'])) {
271 //Check if evening
272 if ($slot == 'Evening') {
273 //Set begin at 19h
274 $session->setBegin(new \DateTime('19:00:00'));
275
276 //Check if next day is premium
277 if ($premium) {
278 //Set length at 7h
279 $session->setLength(new \DateTime('07:00:00'));
280 }
281 //Check if after
282 } else {
283 //Set begin at 1h
284 $session->setBegin(new \DateTime('01:00:00'));
285
286 //Set length at 4h
287 $session->setLength(new \DateTime('04:00:00'));
288
289 //Check if next day is premium
290 if ($premium) {
291 //Set begin at 2h
292 $session->setBegin(new \DateTime('02:00:00'));
293
294 //Set length at 3h
295 $session->setLength(new \DateTime('03:00:00'));
296 }
297 }
298 //Drawings' garden (Villette) => 14h -> 19h
299 } elseif ($location == 'Drawings\' garden' && $slot == 'Afternoon') {
300 //Set begin at 14h
301 $session->setBegin(new \DateTime('14:00:00'));
302
303 //Set length at 5h
304 $session->setLength(new \DateTime('05:00:00'));
305 //Colette place => 14h -> 21h
306 //TODO: add check here that it's a millegaux account ?
307 } elseif ($location == 'Colette place' && $slot == 'Afternoon') {
308 //Set begin at 14h
309 $session->setBegin(new \DateTime('14:00:00'));
310
311 //Set length at 7h
312 $session->setLength(new \DateTime('07:00:00'));
313 //Orleans gallery => 14h -> 18h
314 } elseif ($location == 'Orleans gallery' && $slot == 'Afternoon') {
315 //Set begin at 14h
316 $session->setBegin(new \DateTime('14:00:00'));
317
318 //Set length at 4h
319 $session->setLength(new \DateTime('04:00:00'));
320 //Monde garden => 14h -> 19h
321 //TODO: add check here that it's a raphael account ?
322 } elseif ($location == 'Monde garden' && $slot == 'Afternoon') {
323 //Set begin at 14h
324 $session->setBegin(new \DateTime('14:00:00'));
325
326 //Set length at 4h
327 $session->setLength(new \DateTime('05:00:00'));
328 //Combination not supported
329 //TODO: add Madeleine place|Bastille place|Vendome place ?
330 } else {
331 //Add error in flash message
332 $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(strval($data['slot']))), '%date%' => $data['date']->format('Y-m-d')]));
333
334 //Set title
335 $title = $this->translator->trans('Application add');
336
337 //Render the view
338 return $this->render('@RapsysAir/application/add.html.twig', ['title' => $title, 'form' => $form->createView()]+$this->context);
339 }
340
341 //Check if admin
342 if (!$this->isGranted('ROLE_ADMIN') && $session->getStart() < new \DateTime('00:00:00')) {
343 //Add error in flash message
344 $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(strval($data['slot']))), '%date%' => $data['date']->format('Y-m-d')]));
345
346 //Set title
347 $title = $this->translator->trans('Application add');
348
349 //Render the view
350 return $this->render('@RapsysAir/application/add.html.twig', ['title' => $title, 'form' => $form->createView()]+$this->context);
351 }
352
353 //Queue session save
354 $manager->persist($session);
355
356 //Flush to get the ids
357 #$manager->flush();
358
359 $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(strval($data['slot']))), '%date%' => $data['date']->format('Y-m-d')]));
360 }
361
362 //Set user
363 $user = $this->getUser();
364
365 //Replace with requested user for admin
366 if ($this->isGranted('ROLE_ADMIN') && !empty($data['user'])) {
367 $user = $this->getDoctrine()->getRepository(User::class)->findOneById($data['user']);
368 }
369
370 //Protect application fetching
371 try {
372 //Retrieve application
373 $application = $doctrine->getRepository(Application::class)->findOneBySessionUser($session, $user);
374
375 //Add warning in flash message
376 $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(strval($data['slot']))), '%date%' => $data['date']->format('Y-m-d')]));
377 //Catch no application and session without identifier (not persisted&flushed) cases
378 } catch (NoResultException|ORMInvalidArgumentException $e) {
379 //Create the application
380 $application = new Application();
381 $application->setDance($data['dance']);
382 $application->setSession($session);
383 $application->setUser($user);
384
385 //Refresh session updated field
386 $session->setUpdated(new \DateTime('now'));
387
388 //Queue session save
389 $manager->persist($session);
390
391 //Queue application save
392 $manager->persist($application);
393
394 //Flush to get the ids
395 $manager->flush();
396
397 //Add notice in flash message
398 $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(strval($data['slot']))), '%date%' => $data['date']->format('Y-m-d')]));
399 }
400
401 //Extract and process referer
402 if ($referer = $request->headers->get('referer')) {
403 //Create referer request instance
404 $req = Request::create($referer);
405
406 //Get referer path
407 $path = $req->getPathInfo();
408
409 //Get referer query string
410 $query = $req->getQueryString();
411
412 //Remove script name
413 $path = str_replace($request->getScriptName(), '', $path);
414
415 //Try with referer path
416 try {
417 //Save old context
418 $oldContext = $this->router->getContext();
419
420 //Force clean context
421 //XXX: prevent MethodNotAllowedException because current context method is POST in onevendor/symfony/routing/Matcher/Dumper/CompiledUrlMatcherTrait.php+42
422 $this->router->setContext(new RequestContext());
423
424 //Retrieve route matching path
425 $route = $this->router->match($path);
426
427 //Reset context
428 $this->router->setContext($oldContext);
429
430 //Clear old context
431 unset($oldContext);
432
433 //Extract name
434 $name = $route['_route'];
435
436 //Remove route and controller from route defaults
437 unset($route['_route'], $route['_controller']);
438
439 //Check if session view route
440 if ($name == 'rapsys_air_session_view' && !empty($route['id'])) {
441 //Replace id
442 $route['id'] = $session->getId();
443 //Other routes
444 } else {
445 //Set session
446 $route['session'] = $session->getId();
447 }
448
449 //Generate url
450 return $this->redirectToRoute($name, $route);
451 //No route matched
452 } catch (MethodNotAllowedException|ResourceNotFoundException $e) {
453 //Unset referer to fallback to default route
454 unset($referer);
455 }
456 }
457
458 //Redirect to cleanup the form
459 return $this->redirectToRoute('rapsys_air', ['session' => $session->getId()]);
460 }
461 }