]> Raphaƫl G. Git Repositories - airbundle/blob - Controller/ApplicationController.php
Update css
[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 //Queue session save
88 $manager->persist($session);
89
90 //Flush to get the ids
91 #$manager->flush();
92
93 $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')]));
94 }
95
96 //Set user
97 $user = $this->getUser();
98
99 //Replace with requested user for admin
100 if ($this->isGranted('ROLE_ADMIN') && !empty($data['user'])) {
101 $user = $this->getDoctrine()->getRepository(User::class)->findOneById($data['user']);
102 }
103
104 //Protect application fetching
105 try {
106 //Retrieve application
107 $application = $doctrine->getRepository(Application::class)->findOneBySessionUser($session, $user);
108
109 //Add notice in flash message
110 $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')]));
111 //Catch no application and session without identifier (not persisted&flushed) cases
112 } catch (\Doctrine\ORM\NoResultException|\Doctrine\ORM\ORMInvalidArgumentException $e) {
113 //Create the application
114 $application = new Application();
115 $application->setSession($session);
116 $application->setUser($user);
117 $application->setCreated(new \DateTime('now'));
118 $application->setUpdated(new \DateTime('now'));
119
120 //Refresh session updated field
121 $session->setUpdated(new \DateTime('now'));
122
123 //Queue session save
124 $manager->persist($session);
125
126 //Queue application save
127 $manager->persist($application);
128
129 //Flush to get the ids
130 $manager->flush();
131
132 //Add notice in flash message
133 $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')]));
134 }
135
136 //Extract and process referer
137 if ($referer = $request->headers->get('referer')) {
138 //Create referer request instance
139 $req = Request::create($referer);
140
141 //Get referer path
142 $path = $req->getPathInfo();
143
144 //Get referer query string
145 $query = $req->getQueryString();
146
147 //Remove script name
148 $path = str_replace($request->getScriptName(), '', $path);
149
150 //Try with referer path
151 try {
152 //Save old context
153 $oldContext = $this->router->getContext();
154
155 //Force clean context
156 //XXX: prevent MethodNotAllowedException because current context method is POST in onevendor/symfony/routing/Matcher/Dumper/CompiledUrlMatcherTrait.php+42
157 $this->router->setContext(new RequestContext());
158
159 //Retrieve route matching path
160 $route = $this->router->match($path);
161
162 //Reset context
163 $this->router->setContext($oldContext);
164
165 //Clear old context
166 unset($oldContext);
167
168 //Extract name
169 $name = $route['_route'];
170
171 //Remove route and controller from route defaults
172 unset($route['_route'], $route['_controller']);
173
174 //Generate url
175 return $this->redirectToRoute($name, ['session' => $session->getId()]+$route);
176 //No route matched
177 } catch(ResourceNotFoundException $e) {
178 //Unset referer to fallback to default route
179 unset($referer);
180 }
181 }
182
183 //Redirect to cleanup the form
184 return $this->redirectToRoute('rapsys_air', ['session' => $session->getId()]);
185 }
186 }