]> Raphaƫl G. Git Repositories - airbundle/blob - Controller/DefaultController.php
Cleanup
[airbundle] / Controller / DefaultController.php
1 <?php
2
3 namespace Rapsys\AirBundle\Controller;
4
5 use Rapsys\AirBundle\Entity\Application;
6 use Rapsys\AirBundle\Entity\Location;
7 use Rapsys\AirBundle\Entity\Session;
8 use Rapsys\AirBundle\Entity\Slot;
9 use Rapsys\AirBundle\Entity\User;
10 use Symfony\Bridge\Twig\Mime\TemplatedEmail;
11 use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
12 use Symfony\Component\DependencyInjection\ContainerInterface;
13 use Symfony\Component\Form\FormError;
14 use Symfony\Component\HttpFoundation\Request;
15 use Symfony\Component\HttpFoundation\RequestStack;
16 use Symfony\Component\Mailer\Exception\TransportExceptionInterface;
17 use Symfony\Component\Mailer\MailerInterface;
18 use Symfony\Component\Mime\Address;
19 use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
20 use Symfony\Component\Routing\RouterInterface;
21 use Symfony\Component\Translation\TranslatorInterface;
22 use Rapsys\UserBundle\Utils\Slugger;
23 use Symfony\Bundle\FrameworkBundle\Controller\ControllerTrait;
24 use Symfony\Component\DependencyInjection\ContainerAwareTrait;
25
26
27 class DefaultController {
28 use ControllerTrait;
29
30 ///Config array
31 protected $config;
32
33 ///Context array
34 protected $context;
35
36 ///Router instance
37 protected $router;
38
39 ///Translator instance
40 protected $translator;
41
42 /**
43 * @var ContainerInterface
44 */
45 protected $container;
46
47 /**
48 * Inject container and translator interface
49 *
50 * @param ContainerInterface $container The container instance
51 * @param RouterInterface $router The router instance
52 * @param TranslatorInterface $translator The translator instance
53 */
54 public function __construct(ContainerInterface $container, RouterInterface $router, RequestStack $requestStack, TranslatorInterface $translator) {
55 //Retrieve config
56 $this->config = $container->getParameter($this->getAlias());
57
58 //Set the container
59 $this->container = $container;
60
61 //Set the router
62 $this->router = $router;
63
64 //Set the translator
65 $this->translator = $translator;
66
67 //Set the context
68 $this->context = [
69 'copy' => [
70 'long' => $translator->trans($this->config['copy']['long']),
71 'short' => $translator->trans($this->config['copy']['short'])
72 ],
73 'site' => [
74 'ico' => $this->config['site']['ico'],
75 'logo' => $this->config['site']['logo'],
76 'png' => $this->config['site']['png'],
77 'svg' => $this->config['site']['svg'],
78 'title' => $translator->trans($this->config['site']['title']),
79 'url' => $router->generate($this->config['site']['url']),
80 ],
81 'canonical' => null,
82 'alternates' => []
83 ];
84
85 //Get current locale
86 #$currentLocale = $router->getContext()->getParameters()['_locale'];
87 $currentLocale = $requestStack->getCurrentRequest()->getLocale();
88
89 //Set translator locale
90 //XXX: allow LocaleSubscriber on the fly locale change for first page
91 $this->translator->setLocale($currentLocale);
92
93 //Iterate on locales excluding current one
94 foreach($this->config['locales'] as $locale) {
95 //Set titles
96 $titles = [];
97
98 //Iterate on other locales
99 foreach(array_diff($this->config['locales'], [$locale]) as $other) {
100 $titles[$other] = $translator->trans($this->config['languages'][$locale], [], null, $other);
101 }
102
103 //Get context path
104 $path = $router->getContext()->getPathInfo();
105
106 //Retrieve route matching path
107 $route = $router->match($path);
108
109 //Get route name
110 $name = $route['_route'];
111
112 //Unset route name
113 unset($route['_route']);
114
115 //With current locale
116 if ($locale == $currentLocale) {
117 //Set locale locales context
118 $this->context['canonical'] = $router->generate($name, ['_locale' => $locale]+$route, UrlGeneratorInterface::ABSOLUTE_URL);
119 } else {
120 //Set locale locales context
121 $this->context['alternates'][] = [
122 'lang' => $locale,
123 'absolute' => $router->generate($name, ['_locale' => $locale]+$route, UrlGeneratorInterface::ABSOLUTE_URL),
124 'relative' => $router->generate($name, ['_locale' => $locale]+$route),
125 'title' => implode('/', $titles),
126 'translated' => $translator->trans($this->config['languages'][$locale], [], null, $locale)
127 ];
128 }
129 }
130 }
131
132 /**
133 * The contact page
134 *
135 * @desc Send a contact mail to configured contact
136 *
137 * @param Request $request The request instance
138 * @param MailerInterface $mailer The mailer instance
139 *
140 * @return Response The rendered view or redirection
141 */
142 public function contact(Request $request, MailerInterface $mailer) {
143 //Set section
144 $section = $this->translator->trans('Contact');
145
146 //Set description
147 $this->context['description'] = $this->translator->trans('Contact Libre Air');
148
149 //Set keywords
150 $this->context['keywords'] = [
151 $this->translator->trans('contact'),
152 $this->translator->trans('Libre Air'),
153 $this->translator->trans('outdoor'),
154 $this->translator->trans('Argentine Tango'),
155 $this->translator->trans('calendar')
156 ];
157
158 //Set title
159 $title = $this->translator->trans($this->config['site']['title']).' - '.$section;
160
161 //Create the form according to the FormType created previously.
162 //And give the proper parameters
163 $form = $this->createForm('Rapsys\AirBundle\Form\ContactType', null, [
164 'action' => $this->generateUrl('rapsys_air_contact'),
165 'method' => 'POST'
166 ]);
167
168 if ($request->isMethod('POST')) {
169 // Refill the fields in case the form is not valid.
170 $form->handleRequest($request);
171
172 if ($form->isValid()) {
173 //Get data
174 $data = $form->getData();
175
176 //Create message
177 $message = (new TemplatedEmail())
178 //Set sender
179 ->from(new Address($data['mail'], $data['name']))
180 //Set recipient
181 //XXX: remove the debug set in vendor/symfony/mime/Address.php +46
182 ->to(new Address($this->config['contact']['mail'], $this->config['contact']['name']))
183 //Set subject
184 ->subject($data['subject'])
185
186 //Set path to twig templates
187 ->htmlTemplate('@RapsysAir/mail/contact.html.twig')
188 ->textTemplate('@RapsysAir/mail/contact.text.twig')
189
190 //Set context
191 ->context(
192 [
193 'subject' => $data['subject'],
194 'message' => strip_tags($data['message']),
195 ]+$this->context
196 );
197
198 //Try sending message
199 //XXX: mail delivery may silently fail
200 try {
201 //Send message
202 $mailer->send($message);
203
204 //Redirect on the same route with sent=1 to cleanup form
205 return $this->redirectToRoute($request->get('_route'), ['sent' => 1]+$request->get('_route_params'));
206 //Catch obvious transport exception
207 } catch(TransportExceptionInterface $e) {
208 if ($message = $e->getMessage()) {
209 //Add error message mail unreachable
210 $form->get('mail')->addError(new FormError($this->translator->trans('Unable to contact: %mail%: %message%', ['%mail%' => $this->config['contact']['mail'], '%message%' => $this->translator->trans($message)])));
211 } else {
212 //Add error message mail unreachable
213 $form->get('mail')->addError(new FormError($this->translator->trans('Unable to contact: %mail%', ['%mail%' => $this->config['contact']['mail']])));
214 }
215 }
216 }
217 }
218
219 //Render template
220 return $this->render('@RapsysAir/form/contact.html.twig', ['title' => $title, 'section' => $section, 'form' => $form->createView(), 'sent' => $request->query->get('sent', 0)]+$this->context);
221 }
222
223 /**
224 * The index page
225 *
226 * @desc Display all granted sessions with an application or login form
227 *
228 * @param Request $request The request instance
229 *
230 * @return Response The rendered view
231 */
232 public function index(Request $request) {
233 //Fetch doctrine
234 $doctrine = $this->getDoctrine();
235
236 //Set section
237 $section = $this->translator->trans('Argentine Tango in Paris');
238
239 //Set description
240 $this->context['description'] = $this->translator->trans('Outdoor Argentine Tango session calendar in Paris');
241
242 //Set keywords
243 $this->context['keywords'] = [
244 $this->translator->trans('Argentine Tango'),
245 $this->translator->trans('Paris'),
246 $this->translator->trans('outdoor'),
247 $this->translator->trans('calendar'),
248 $this->translator->trans('Libre Air')
249 ];
250
251 //Set title
252 $title = $this->translator->trans($this->config['site']['title']).' - '.$section;
253
254 //Init context
255 $context = [];
256
257 //Create application form for role_guest
258 if ($this->isGranted('ROLE_GUEST')) {
259 //Create ApplicationType form
260 $application = $this->createForm('Rapsys\AirBundle\Form\ApplicationType', null, [
261 //Set the action
262 'action' => $this->generateUrl('rapsys_air_application_add'),
263 //Set the form attribute
264 'attr' => [ 'class' => 'col' ],
265 //Set admin
266 'admin' => $this->isGranted('ROLE_ADMIN'),
267 //Set default user to current
268 'user' => $this->getUser()->getId(),
269 //Set default slot to evening
270 //XXX: default to Evening (3)
271 'slot' => $doctrine->getRepository(Slot::class)->findOneById(3)
272 ]);
273
274 //Add form to context
275 $context['application'] = $application->createView();
276 //Create login form for anonymous
277 } elseif (!$this->isGranted('IS_AUTHENTICATED_REMEMBERED')) {
278 //Create ApplicationType form
279 $login = $this->createForm('Rapsys\UserBundle\Form\LoginType', null, [
280 //Set the action
281 'action' => $this->generateUrl('rapsys_user_login'),
282 //Set the form attribute
283 'attr' => [ 'class' => 'col' ]
284 ]);
285
286 //Add form to context
287 $context['login'] = $login->createView();
288 }
289
290 //Compute period
291 $period = new \DatePeriod(
292 //Start from first monday of week
293 new \DateTime('Monday this week'),
294 //Iterate on each day
295 new \DateInterval('P1D'),
296 //End with next sunday and 4 weeks
297 new \DateTime('Monday this week + 5 week')
298 );
299
300 //Fetch calendar
301 $calendar = $doctrine->getRepository(Session::class)->fetchCalendarByDatePeriod($this->translator, $period, null, $request->get('session'), !$this->isGranted('IS_AUTHENTICATED_REMEMBERED'));
302
303 //Fetch locations
304 //XXX: we want to display all active locations anyway
305 $locations = $doctrine->getRepository(Location::class)->findTranslatedSortedByPeriod($this->translator, $period/*, !$this->isGranted('IS_AUTHENTICATED_REMEMBERED')*/);
306
307 //Render the view
308 return $this->render('@RapsysAir/default/index.html.twig', ['title' => $title, 'section' => $section, 'calendar' => $calendar, 'locations' => $locations]+$context+$this->context);
309 }
310
311 /**
312 * The organizer regulation page
313 *
314 * @desc Display the organizer regulation policy
315 *
316 * @return Response The rendered view
317 */
318 public function organizerRegulation() {
319 //Set section
320 $section = $this->translator->trans('Organizer regulation');
321
322 //Set description
323 $this->context['description'] = $this->translator->trans('Libre Air organizer regulation');
324
325 //Set keywords
326 $this->context['keywords'] = [
327 $this->translator->trans('organizer regulation'),
328 $this->translator->trans('Libre Air')
329 ];
330
331 //Set title
332 $title = $this->translator->trans($this->config['site']['title']).' - '.$section;
333
334 //Render template
335 return $this->render('@RapsysAir/default/organizer_regulation.html.twig', ['title' => $title, 'section' => $section]+$this->context);
336 }
337
338 /**
339 * The terms of service page
340 *
341 * @desc Display the terms of service policy
342 *
343 * @return Response The rendered view
344 */
345 public function termsOfService() {
346 //Set section
347 $section = $this->translator->trans('Terms of service');
348
349 //Set description
350 $this->context['description'] = $this->translator->trans('Libre Air terms of service');
351
352 //Set keywords
353 $this->context['keywords'] = [
354 $this->translator->trans('terms of service'),
355 $this->translator->trans('Libre Air')
356 ];
357
358 //Set title
359 $title = $this->translator->trans($this->config['site']['title']).' - '.$section;
360
361 //Render template
362 return $this->render('@RapsysAir/default/terms_of_service.html.twig', ['title' => $title, 'section' => $section]+$this->context);
363 }
364
365 /**
366 * Return the bundle alias
367 *
368 * {@inheritdoc}
369 */
370 public function getAlias() {
371 return 'rapsys_air';
372 }
373 }