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