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