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