]> Raphaƫl G. Git Repositories - airbundle/blob - Controller/ApplicationController.php
Rename ROLE_USER to User
[airbundle] / Controller / ApplicationController.php
1 <?php
2
3 namespace Rapsys\AirBundle\Controller;
4
5 use Symfony\Component\HttpFoundation\Request;
6 use Rapsys\AirBundle\Entity\Slot;
7 use Rapsys\AirBundle\Entity\User;
8 use Rapsys\AirBundle\Entity\Session;
9 use Rapsys\AirBundle\Entity\Application;
10
11 class ApplicationController extends DefaultController {
12 /**
13 * Add application
14 *
15 * @desc Persist application and all required dependencies in database
16 *
17 * @param Request $request The request instance
18 *
19 * @return Response The rendered view or redirection
20 *
21 * @throws \RuntimeException When user has not at least guest role
22 */
23 public function add(Request $request) {
24 //Prevent non-guest to access here
25 $this->denyAccessUnlessGranted('ROLE_GUEST', null, $this->translator->trans('Unable to access this page without role %role%!', ['%role%' => $this->translator->trans('Guest')]));
26
27 //Create ApplicationType form
28 $form = $this->createForm('Rapsys\AirBundle\Form\ApplicationType', null, [
29 //Set the action
30 'action' => $this->generateUrl('rapsys_air_application_add'),
31 //Set the form attribute
32 #'attr' => [ 'class' => 'col' ],
33 //Set admin
34 'admin' => $this->isGranted('ROLE_ADMIN'),
35 //Set default user to current
36 'user' => $this->getUser()->getId(),
37 //Set default slot to evening
38 //XXX: default to Evening (3)
39 'slot' => $this->getDoctrine()->getRepository(Slot::class)->findOneById(3)
40 ]);
41
42 //Reject non post requests
43 if (!$request->isMethod('POST')) {
44 throw new \RuntimeException('Request method MUST be POST');
45 }
46
47 //Refill the fields in case of invalid form
48 $form->handleRequest($request);
49
50 //Handle invalid form
51 if (!$form->isValid()) {
52 //Set section
53 $section = $this->translator->trans('Application Add');
54
55 //Set title
56 $title = $section.' - '.$this->translator->trans($this->config['site']['title']);
57
58 //Render the view
59 return $this->render('@RapsysAir/application/add.html.twig', ['title' => $title, 'section' => $section, 'form' => $form]+$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 //Queue session save
86 $manager->persist($session);
87
88 //Flush to get the ids
89 #$manager->flush();
90
91 $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')]));
92 }
93
94 //Set user
95 $user = $this->getUser();
96
97 //Replace with requested user for admin
98 if ($this->isGranted('ROLE_ADMIN') && !empty($data['user'])) {
99 $user = $this->getDoctrine()->getRepository(User::class)->findOneById($data['user']);
100 }
101
102 //Protect application fetching
103 try {
104 //Retrieve application
105 $application = $doctrine->getRepository(Application::class)->findOneBySessionUser($session, $user);
106
107 //Add notice in flash message
108 //TODO: set warning about application already exists bla bla bla...
109 #$this->addFlash('notice', $this->translator->trans('Application request the %date% for %location% on the slot %slot% saved', ['%location%' => $data['location']->getTitle(), '%slot%' => $data['slot']->getTitle(), '%date%' => $data['date']->format('Y-m-d')]));
110
111 //Add error message to mail field
112 #$form->get('slot')->addError(new FormError($this->translator->trans('Application already exists')));
113
114 //TODO: redirect anyway on uri with application highlighted
115 //Catch no application and session without identifier (not persisted&flushed) cases
116 } catch (\Doctrine\ORM\NoResultException|\Doctrine\ORM\ORMInvalidArgumentException $e) {
117 //Create the application
118 $application = new Application();
119 $application->setSession($session);
120 $application->setUser($user);
121 $application->setCreated(new \DateTime('now'));
122 $application->setUpdated(new \DateTime('now'));
123
124 //Refresh session updated field
125 $session->setUpdated(new \DateTime('now'));
126
127 //Queue session save
128 $manager->persist($session);
129
130 //Queue application save
131 $manager->persist($application);
132
133 //Flush to get the ids
134 #$manager->flush();
135
136 //Add notice in flash message
137 $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')]));
138 }
139
140 //Try unshort return field
141 if (
142 !empty($data['return']) &&
143 ($unshort = $this->slugger->unshort($data['return'])) &&
144 ($route = json_decode($unshort, true)) !== null
145 ) {
146 $return = $this->generateUrl($route['_route'], ['session' => $session->getId()?:1]+$route['_route_params']);
147 }
148
149 //XXX: Debug
150 header('Content-Type: text/plain');
151
152 //Extract and process referer
153 if ($referer = $request->headers->get('referer')) {
154 //Create referer request instance
155 $req = Request::create($referer);
156
157 //Get referer path
158 $path = $req->getPathInfo();
159
160 //Get referer query string
161 $query = $req->getQueryString();
162
163 //Remove script name
164 $path = str_replace($request->getScriptName(), '', $path);
165
166 //Try with referer path
167 try {
168 var_dump($this->router);
169 exit;
170 var_dump($path = '/location');
171 var_dump($this->router->match($path));
172 var_dump($path = '/fr/emplacement');
173 exit;
174 var_dump($this->router->match());
175 exit;
176 var_dump($path);
177 var_dump($query);
178 exit;
179 //Retrieve route matching path
180 $route = $this->router->match($path);
181 var_dump($route);
182 exit;
183
184 //Verify that it differ from current one
185 if (($name = $route['_route']) == $logout) {
186 throw new ResourceNotFoundException('Identical referer and logout route');
187 }
188
189 //Remove route and controller from route defaults
190 unset($route['_route'], $route['_controller']);
191
192 //Generate url
193 $url = $this->router->generate($name, $route);
194 //No route matched
195 } catch(ResourceNotFoundException $e) {
196 //Unset referer to fallback to default route
197 unset($referer);
198 }
199 }
200 var_dump($request->headers->get('referer'));
201 #var_dump($request->get('_route'));
202
203 var_dump($return);
204 exit;
205
206 //Fetch slugger helper
207 $slugger = $this->get('rapsys.slugger');
208
209 var_dump($short = $slugger->short(json_encode(['_route' => $request->get('_route'), '_route_params' => $request->get('_route_params')])));
210 $short[12] = 'T';
211 var_dump($ret = json_decode($slugger->unshort($short), true));
212 var_dump($ret);
213 var_dump($this->generateUrl($ret['_route'], $ret['_route_params']));
214 #var_dump(json_decode($slugger->unshort($data['return'])));
215 #var_dump($application->getId());
216 exit;
217
218 //Init application
219 $application = false;
220
221 //Protect application fetching
222 try {
223 //TODO: handle admin case where we provide a user in extra
224 $application = $doctrine->getRepository(Application::class)->findOneBySessionUser($session, $this->getUser());
225
226 //Add error message to mail field
227 $form->get('slot')->addError(new FormError($this->translator->trans('Application already exists')));
228 //Catch no application cases
229 //XXX: combine these catch when php 7.1 is available
230 } catch (\Doctrine\ORM\NoResultException $e) {
231 //Catch invalid argument because session is not already persisted
232 } catch(\Doctrine\ORM\ORMInvalidArgumentException $e) {
233 }
234
235 //Create new application if none found
236 if (!$application) {
237 //Create the application
238 $application = new Application();
239 $application->setSession($session);
240 //TODO: handle admin case where we provide a user in extra
241 $application->setUser($this->getUser());
242 $application->setCreated(new \DateTime('now'));
243 $application->setUpdated(new \DateTime('now'));
244 $manager->persist($application);
245
246 //Flush to get the ids
247 $manager->flush();
248
249 //Add notice in flash message
250 $this->addFlash('notice', $this->translator->trans('Application request the %date% for %location% on the slot %slot% saved', ['%location%' => $data['location']->getTitle(), '%slot%' => $data['slot']->getTitle(), '%date%' => $data['date']->format('Y-m-d')]));
251
252 //Redirect to cleanup the form
253 return $this->redirectToRoute('rapsys_air_admin');
254 }
255 }
256
257 function test(Request $request) {
258
259 //Compute period
260 $period = new \DatePeriod(
261 //Start from first monday of week
262 new \DateTime('Monday this week'),
263 //Iterate on each day
264 new \DateInterval('P1D'),
265 //End with next sunday and 4 weeks
266 new \DateTime('Monday this week + 5 week')
267 );
268
269 //Fetch sessions
270 $sessions = $doctrine->getRepository(Session::class)->findAllByDatePeriod($period);
271
272 //Init calendar
273 $calendar = [];
274
275 //Init month
276 $month = null;
277
278 //Iterate on each day
279 foreach($period as $date) {
280 //Init day in calendar
281 $calendar[$Ymd = $date->format('Ymd')] = [
282 'title' => $date->format('d'),
283 'class' => [],
284 'sessions' => []
285 ];
286 //Append month for first day of month
287 if ($month != $date->format('m')) {
288 $month = $date->format('m');
289 $calendar[$Ymd]['title'] .= '/'.$month;
290 }
291 //Deal with today
292 if ($date->format('U') == ($today = strtotime('today'))) {
293 $calendar[$Ymd]['title'] .= '/'.$month;
294 $calendar[$Ymd]['current'] = true;
295 $calendar[$Ymd]['class'][] = 'current';
296 }
297 //Disable passed days
298 if ($date->format('U') < $today) {
299 $calendar[$Ymd]['disabled'] = true;
300 $calendar[$Ymd]['class'][] = 'disabled';
301 }
302 //Set next month days
303 if ($date->format('m') > date('m')) {
304 $calendar[$Ymd]['next'] = true;
305 $calendar[$Ymd]['class'][] = 'next';
306 }
307 //Iterate on each session to find the one of the day
308 foreach($sessions as $session) {
309 if (($sessionYmd = $session->getDate()->format('Ymd')) == $Ymd) {
310 //Count number of application
311 $count = count($session->getApplications());
312
313 //Compute classes
314 $class = [];
315 if ($session->getApplication()) {
316 $class[] = 'granted';
317 } elseif ($count == 0) {
318 $class[] = 'orphaned';
319 } elseif ($count > 1) {
320 $class[] = 'disputed';
321 } else {
322 $class[] = 'pending';
323 }
324
325 //Add the session
326 $calendar[$Ymd]['sessions'][$session->getSlot()->getId().$session->getLocation()->getId()] = [
327 'id' => $session->getId(),
328 'title' => ($count > 1?'['.$count.'] ':'').$session->getSlot()->getTitle().' '.$session->getLocation()->getTitle(),
329 'class' => $class
330 ];
331 }
332 }
333
334 //Sort sessions
335 ksort($calendar[$Ymd]['sessions']);
336 }
337 }
338 }