]> Raphaƫl G. Git Repositories - airbundle/blob - Controller/DefaultController.php
Move the configuration in rapsys_air key
[airbundle] / Controller / DefaultController.php
1 <?php
2
3 namespace Rapsys\AirBundle\Controller;
4
5 #use Symfony\Bundle\FrameworkBundle\Controller\Controller;
6 use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
7 use Psr\Container\ContainerInterface;
8 use Symfony\Bundle\FrameworkBundle\Translation\Translator;
9 use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
10 use Symfony\Component\HttpFoundation\Request;
11 use Rapsys\AirBundle\Entity\Session;
12 use Rapsys\AirBundle\Entity\Application;
13 use Symfony\Component\Form\FormError;
14
15 #class DefaultController extends Controller {
16 class DefaultController extends AbstractController {
17 //Container instance
18 protected $container;
19
20 //Translator instance
21 protected $translator;
22
23 public function __construct(ContainerInterface $container, Translator $translator) {
24 //Set the container
25 $this->container = $container;
26
27 //Set the translator
28 $this->translator = $translator;
29 }
30
31 //FIXME: we need to change the $this->container->getParameter($alias.'.xyz') to $this->container->getParameter($alias)['xyz']
32 public function contactAction(Request $request) {
33 //Set section
34 $section = $this->translator->trans('Contact');
35
36 //Set title
37 $title = $section.' - '.$this->translator->trans($this->container->getParameter('rapsys_air.title'));
38
39 //Create the form according to the FormType created previously.
40 //And give the proper parameters
41 $form = $this->createForm('Rapsys\AirBundle\Form\ContactType', null, [
42 // To set the action use $this->generateUrl('route_identifier')
43 'action' => $this->generateUrl('rapsys_air_contact'),
44 'method' => 'POST'
45 ]);
46
47 if ($request->isMethod('POST')) {
48 // Refill the fields in case the form is not valid.
49 $form->handleRequest($request);
50
51 if ($form->isValid()) {
52 //Get data
53 $data = $form->getData();
54
55 //Get contact name
56 $contactName = $this->container->getParameter('rapsys_air.contact_name');
57
58 //Get contact mail
59 $contactMail = $this->container->getParameter('rapsys_air.contact_mail');
60
61 //Get logo
62 $logo = $this->container->getParameter('rapsys_air.logo');
63
64 //Get title
65 $title = $this->translator->trans($this->container->getParameter('rapsys_air.title'));
66
67 //Get subtitle
68 $subtitle = $this->translator->trans('Hi,').' '.$contactName;
69
70 //Create sendmail transport
71 $transport = new \Swift_SendmailTransport();
72
73 //Create mailer using transport
74 $mailer = new \Swift_Mailer($transport);
75
76 //Create the message
77 ($message = new \Swift_Message($data['subject']))
78 #->setSubject($data['subject'])
79 ->setFrom([$data['mail'] => $data['name']])
80 ->setTo([$contactMail => $contactName])
81 ->setBody($data['message'])
82 ->addPart(
83 $this->renderView(
84 '@RapsysAir/mail/generic.html.twig',
85 [
86 'logo' => $logo,
87 'title' => $title,
88 'subtitle' => $subtitle,
89 'home' => $this->get('router')->generate('rapsys_air_homepage', [], UrlGeneratorInterface::ABSOLUTE_URL),
90 'subject' => $data['subject'],
91 'contact_name' => $contactName,
92 'message' => strip_tags($data['message'])
93 ]
94 ),
95 'text/html'
96 );
97
98 //Send the message
99 if ($mailer->send($message)) {
100 //Redirect to cleanup the form
101 return $this->redirectToRoute('rapsys_air_contact', ['sent' => 1]);
102 }
103 }
104 }
105
106 //Render template
107 return $this->render('@RapsysAir/form/contact.html.twig', ['title' => $title, 'section' => $section, 'form' => $form->createView(), 'sent' => $request->query->get('sent', 0)]);
108 }
109
110 public function indexAction() {
111 //Set section
112 $section = $this->translator->trans('Index');
113
114 //Set title
115 $title = $section.' - '.$this->translator->trans($this->container->getParameter('rapsys_air.title'));
116
117 //Render template
118 return $this->render('@RapsysAir/page/index.html.twig', ['title' => $title, 'section' => $section]);
119 }
120
121 public function adminAction(Request $request) {
122 //Prevent non-admin to access here
123 //TODO: maybe check if user is connected 1st ?
124 $this->denyAccessUnlessGranted('ROLE_ADMIN', null, 'Unable to access this page!');
125
126 //Set section
127 $section = $this->translator->trans('Admin');
128
129 //Set title
130 $title = $section.' - '.$this->translator->trans($this->container->getParameter('rapsys_air.title'));
131
132 //Create the form according to the FormType created previously.
133 //And give the proper parameters
134 $form = $this->createForm('Rapsys\AirBundle\Form\ApplicationType', null, [
135 // To set the action use $this->generateUrl('route_identifier')
136 'action' => $this->generateUrl('rapsys_air_admin'),
137 'method' => 'POST',
138 'attr' => [ 'class' => 'form_col' ]
139 ]);
140
141 //Get doctrine
142 $doctrine = $this->getDoctrine();
143
144 //Handle request
145 if ($request->isMethod('POST')) {
146 // Refill the fields in case the form is not valid.
147 $form->handleRequest($request);
148
149 if ($form->isValid()) {
150 //Get data
151 $data = $form->getData();
152
153 //Get manager
154 $manager = $doctrine->getManager();
155
156 //Protect session fetching
157 try {
158 $session = $doctrine->getRepository(Session::class)->findOneByLocationSlotDate($data['location'], $data['slot'], $data['date']);
159 //Catch no session case
160 } catch (\Doctrine\ORM\NoResultException $e) {
161 //Create the session
162 $session = new Session();
163 $session->setLocation($data['location']);
164 $session->setSlot($data['slot']);
165 $session->setDate($data['date']);
166 $session->setCreated(new \DateTime('now'));
167 $session->setUpdated(new \DateTime('now'));
168 $manager->persist($session);
169 //Flush to get the ids
170 #$manager->flush();
171 }
172
173 //Init application
174 $application = false;
175
176 //Protect application fetching
177 try {
178 //TODO: handle admin case where we provide a user in extra
179 $application = $doctrine->getRepository(Application::class)->findOneBySessionUser($session, $this->getUser());
180
181 //Add error message to mail field
182 $form->get('slot')->addError(new FormError($this->translator->trans('Application already exists')));
183 //Catch no application cases
184 //XXX: combine these catch when php 7.1 is available
185 } catch (\Doctrine\ORM\NoResultException $e) {
186 //Catch invalid argument because session is not already persisted
187 } catch(\Doctrine\ORM\ORMInvalidArgumentException $e) {
188 }
189
190 //Create new application if none found
191 if (!$application) {
192 //Create the application
193 $application = new Application();
194 $application->setSession($session);
195 //TODO: handle admin case where we provide a user in extra
196 $application->setUser($this->getUser());
197 $application->setCreated(new \DateTime('now'));
198 $application->setUpdated(new \DateTime('now'));
199 $manager->persist($application);
200
201 //Flush to get the ids
202 $manager->flush();
203
204 //Add notice in flash message
205 $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')]));
206
207 //Redirect to cleanup the form
208 return $this->redirectToRoute('rapsys_air_admin');
209 }
210 }
211 }
212
213 //Compute period
214 $period = new \DatePeriod(
215 //Start from first monday of week
216 new \DateTime('Monday this week'),
217 //Iterate on each day
218 new \DateInterval('P1D'),
219 //End with next sunday and 4 weeks
220 new \DateTime('Monday this week + 5 week')
221 );
222
223 //Fetch sessions
224 $sessions = $doctrine->getRepository(Session::class)->findByDatePeriod($period);
225
226 //Init calendar
227 $calendar = [];
228
229 //Init month
230 $month = null;
231
232 //Iterate on each day
233 foreach($period as $date) {
234 //Init day in calendar
235 $calendar[$Ymd = $date->format('Ymd')] = [
236 'title' => $date->format('d'),
237 'class' => [],
238 'sessions' => []
239 ];
240 //Append month for first day of month
241 if ($month != $date->format('m')) {
242 $month = $date->format('m');
243 $calendar[$Ymd]['title'] .= '/'.$month;
244 }
245 //Deal with today
246 if ($date->format('U') == ($today = strtotime('today'))) {
247 $calendar[$Ymd]['title'] .= '/'.$month;
248 $calendar[$Ymd]['current'] = true;
249 $calendar[$Ymd]['class'][] = 'current';
250 }
251 //Disable passed days
252 if ($date->format('U') < $today) {
253 $calendar[$Ymd]['disabled'] = true;
254 $calendar[$Ymd]['class'][] = 'disabled';
255 }
256 //Set next month days
257 if ($date->format('m') > date('m')) {
258 $calendar[$Ymd]['next'] = true;
259 $calendar[$Ymd]['class'][] = 'next';
260 }
261 //Iterate on each session to find the one of the day
262 foreach($sessions as $session) {
263 if (($sessionYmd = $session->getDate()->format('Ymd')) == $Ymd) {
264 //Count number of application
265 $count = count($session->getApplications());
266
267 //Compute classes
268 $class = [];
269 if ($session->getApplication()) {
270 $class[] = 'granted';
271 } elseif ($count == 0) {
272 $class[] = 'orphaned';
273 } elseif ($count > 1) {
274 $class[] = 'disputed';
275 } else {
276 $class[] = 'pending';
277 }
278
279 //Add the session
280 $calendar[$Ymd]['sessions'][$session->getSlot()->getId().$session->getLocation()->getId()] = [
281 'id' => $session->getId(),
282 'title' => ($count > 1?'['.$count.'] ':'').$session->getSlot()->getTitle().' '.$session->getLocation()->getTitle(),
283 'class' => $class
284 ];
285 }
286 }
287
288 //Sort sessions
289 ksort($calendar[$Ymd]['sessions']);
290 }
291
292 return $this->render('@RapsysAir/admin/index.html.twig', ['title' => $title, 'section' => $section, 'form' => $form->createView(), 'calendar' => $calendar]);
293 }
294
295 public function sessionAction(Request $request, $id) {
296 /*header('Content-Type: text/plain');
297 var_dump($calendar);
298 exit;*/
299
300 //Set section
301 $section = $this->translator->trans('Session %id%', ['%id%' => $id]);
302
303 //Set title
304 $title = $section.' - '.$this->translator->trans($this->container->getParameter('rapsys_air.title'));
305
306 //Create the form according to the FormType created previously.
307 //And give the proper parameters
308 /*$form = $this->createForm('Rapsys\AirBundle\Form\ApplicationType', null, [
309 // To set the action use $this->generateUrl('route_identifier')
310 'action' => $this->generateUrl('rapsys_air_admin'),
311 'method' => 'POST',
312 'attr' => [ 'class' => 'form_col' ]
313 ]);*/
314
315 //Get doctrine
316 $doctrine = $this->getDoctrine();
317
318 //Fetch session
319 $session = $doctrine->getRepository(Session::class)->findOneById($id);
320
321 return $this->render('@RapsysAir/admin/session.html.twig', ['title' => $title, 'section' => $section, /*'form' => $form->createView(),*/ 'session' => $session]);
322 }
323 }