]> Raphaël G. Git Repositories - airbundle/blob - Controller/AbstractController.php
Drop map util helper
[airbundle] / Controller / AbstractController.php
1 <?php declare(strict_types=1);
2
3 /*
4 * This file is part of the Rapsys AirBundle package.
5 *
6 * (c) Raphaël Gertz <symfony@rapsys.eu>
7 *
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
10 */
11
12 namespace Rapsys\AirBundle\Controller;
13
14 use Doctrine\ORM\EntityManagerInterface;
15 use Doctrine\Persistence\ManagerRegistry;
16
17 use Psr\Container\ContainerInterface;
18 use Psr\Log\LoggerInterface;
19
20 use Symfony\Bundle\FrameworkBundle\Controller\AbstractController as BaseAbstractController;
21 use Symfony\Bundle\SecurityBundle\Security;
22 use Symfony\Component\Asset\PackageInterface;
23 use Symfony\Component\Filesystem\Exception\IOExceptionInterface;
24 use Symfony\Component\Filesystem\Filesystem;
25 use Symfony\Component\Form\FormFactoryInterface;
26 use Symfony\Component\HttpFoundation\Request;
27 use Symfony\Component\HttpFoundation\RequestStack;
28 use Symfony\Component\HttpFoundation\Response;
29 use Symfony\Component\Mailer\MailerInterface;
30 use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
31 use Symfony\Component\Routing\RouterInterface;
32 use Symfony\Component\Security\Core\Authorization\AccessDecisionManagerInterface;
33 use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
34 use Symfony\Contracts\Service\ServiceSubscriberInterface;
35 use Symfony\Contracts\Translation\TranslatorInterface;
36
37 use Twig\Environment;
38
39 use Rapsys\AirBundle\Entity\Dance;
40 use Rapsys\AirBundle\Entity\Location;
41 use Rapsys\AirBundle\Entity\Slot;
42 use Rapsys\AirBundle\Entity\User;
43 use Rapsys\AirBundle\RapsysAirBundle;
44
45 use Rapsys\PackBundle\Util\FacebookUtil;
46 use Rapsys\PackBundle\Util\ImageUtil;
47 use Rapsys\PackBundle\Util\SluggerUtil;
48
49 /**
50 * Provides common features needed in controllers.
51 *
52 * {@inheritdoc}
53 */
54 abstract class AbstractController extends BaseAbstractController implements ServiceSubscriberInterface {
55 /**
56 * Config array
57 */
58 protected array $config;
59
60 /**
61 * Context array
62 */
63 protected array $context;
64
65 /**
66 * Locale string
67 */
68 protected string $locale;
69
70 /**
71 * Modified DateTime
72 */
73 protected \DateTimeImmutable $modified;
74
75 /**
76 * DatePeriod instance
77 */
78 protected \DatePeriod $period;
79
80 /**
81 * Request instance
82 */
83 protected Request $request;
84
85 /**
86 * Route string
87 */
88 protected string $route;
89
90 /**
91 * Route params array
92 */
93 protected array $routeParams;
94
95 /**
96 * Abstract constructor
97 *
98 * @param AuthorizationCheckerInterface $checker The container instance
99 * @param ContainerInterface $container The container instance
100 * @param AccessDecisionManagerInterface $decision The decision instance
101 * @param ManagerRegistry $doctrine The doctrine instance
102 * @param FacebookUtil $facebook The facebook instance
103 * @param FormFactoryInterface $factory The factory instance
104 * @param ImageUtil $image The image instance
105 * @param MailerInterface $mailer The mailer instance
106 * @param EntityManagerInterface $manager The manager instance
107 * @param PackageInterface $package The package instance
108 * @param RouterInterface $router The router instance
109 * @param Security $security The security instance
110 * @param SluggerUtil $slugger The slugger instance
111 * @param RequestStack $stack The stack instance
112 * @param TranslatorInterface $translator The translator instance
113 * @param Environment $twig The twig environment instance
114 *
115 * @TODO move all that stuff to setSlugger('@slugger') setters with a calls: [ setSlugger: [ '@slugger' ] ] to unbload classes ???
116 * @TODO add a calls: [ ..., prepare: ['@???'] ] that do all the logic that can't be done in constructor because various things are not available
117 */
118 public function __construct(protected AuthorizationCheckerInterface $checker, protected ContainerInterface $container, protected AccessDecisionManagerInterface $decision, protected ManagerRegistry $doctrine, protected FacebookUtil $facebook, protected FormFactoryInterface $factory, protected ImageUtil $image, protected MailerInterface $mailer, protected EntityManagerInterface $manager, protected PackageInterface $package, protected RouterInterface $router, protected Security $security, protected SluggerUtil $slugger, protected RequestStack $stack, protected TranslatorInterface $translator, protected Environment $twig, protected int $limit = 5) {
119 //Retrieve config
120 $this->config = $container->getParameter(RapsysAirBundle::getAlias());
121
122 //Set period
123 $this->period = new \DatePeriod(
124 //Start from first monday of week
125 new \DateTime('Monday this week'),
126 //Iterate on each day
127 new \DateInterval('P1D'),
128 //End with next sunday and 4 weeks
129 //XXX: we can't use isGranted here as AuthenticatedVoter deny access because user is likely not authenticated yet :'(
130 new \DateTime('Monday this week + 2 week')
131 );
132
133 //Get main request
134 $this->request = $this->stack->getMainRequest();
135
136 //Get current locale
137 $this->locale = $this->request->getLocale();
138
139 //Set canonical
140 $canonical = null;
141
142 //Set alternates
143 $alternates = [];
144
145 //Set route
146 //TODO: default to not found route ???
147 //TODO: pour une url not found, cet attribut n'est pas défini, comment on fait ???
148 //XXX: on génère une route bidon par défaut ???
149 $this->route = $this->request->attributes->get('_route');
150
151 //Set route params
152 $this->routeParams = $this->request->attributes->get('_route_params');
153
154 //With route and routeParams
155 if ($this->route !== null && $this->routeParams !== null) {
156 //Set canonical
157 $canonical = $this->router->generate($this->route, $this->routeParams, UrlGeneratorInterface::ABSOLUTE_URL);
158
159 //Set alternates
160 $alternates = [
161 substr($this->locale, 0, 2) => [
162 'absolute' => $canonical
163 ]
164 ];
165 }
166
167 //Set the context
168 $this->context = [
169 'alternates' => $alternates,
170 'canonical' => $canonical,
171 'contact' => [
172 'address' => $this->config['contact']['address'],
173 'name' => $this->translator->trans($this->config['contact']['name'])
174 ],
175 'copy' => [
176 'by' => $this->translator->trans($this->config['copy']['by']),
177 'link' => $this->config['copy']['link'],
178 'long' => $this->translator->trans($this->config['copy']['long']),
179 'short' => $this->translator->trans($this->config['copy']['short']),
180 'title' => $this->config['copy']['title']
181 ],
182 'description' => null,
183 'donate' => $this->config['donate'],
184 'facebook' => [
185 'og:type' => 'article',
186 'og:site_name' => $title = $this->translator->trans($this->config['title']),
187 'og:url' => $canonical,
188 #'fb:admins' => $this->config['facebook']['admins'],
189 'fb:app_id' => $this->config['facebook']['apps']
190 ],
191 //XXX: TODO: only generate it when fb robot request the url ???
192 'fbimage' => [
193 'texts' => [
194 $title => [
195 'font' => 'irishgrover',
196 'size' => 110
197 ]
198 ]
199 ],
200 'icon' => $this->config['icon'],
201 'keywords' => null,
202 'locale' => str_replace('_', '-', $this->locale),
203 'logo' => $this->config['logo'],
204 'forms' => [],
205 'root' => $this->router->generate($this->config['root']),
206 'title' => [
207 'page' => null,
208 'section' => null,
209 'site' => $title
210 ]
211 ];
212 }
213
214 /**
215 * Renders a view
216 *
217 * {@inheritdoc}
218 */
219 protected function render(string $view, array $parameters = [], ?Response $response = null): Response {
220 //Create response when null
221 $response ??= new Response();
222
223 //Create application form for role_guest
224 if ($this->checker->isGranted('ROLE_GUEST')) {
225 //Without application form
226 if (empty($parameters['forms']['application'])) {
227 //Get favorites dances
228 $danceFavorites = $this->doctrine->getRepository(Dance::class)->findByUserId($this->security->getUser()->getId());
229
230 //Set dance default
231 $danceDefault = !empty($danceFavorites)?current($danceFavorites):null;
232
233 //Get favorites locations
234 $locationFavorites = $this->doctrine->getRepository(Location::class)->findByUserId($this->security->getUser()->getId());
235
236 //Set location default
237 $locationDefault = !empty($locationFavorites)?current($locationFavorites):null;
238
239 //With admin
240 if ($this->checker->isGranted('ROLE_ADMIN')) {
241 //Get dances
242 $dances = $this->doctrine->getRepository(Dance::class)->findAll();
243
244 //Get locations
245 $locations = $this->doctrine->getRepository(Location::class)->findAll();
246 //Without admin
247 } else {
248 //Restrict to favorite dances
249 $dances = $danceFavorites;
250
251 //Reset favorites
252 $danceFavorites = [];
253
254 //Restrict to favorite locations
255 $locations = $locationFavorites;
256
257 //Reset favorites
258 $locationFavorites = [];
259 }
260
261 //With session application dance id
262 if (!empty($parameters['session']['application']['dance']['id'])) {
263 //Iterate on each dance
264 foreach($dances as $dance) {
265 //Found dance
266 if ($dance->getId() == $parameters['session']['application']['dance']['id']) {
267 //Set dance as default
268 $danceDefault = $dance;
269
270 //Stop search
271 break;
272 }
273 }
274 }
275
276 //With session location id
277 //XXX: set in session controller
278 //TODO: with new findAll that key by id, it should be as simple as isset($locations[$id]) ?
279 if (!empty($parameters['session']['location']['id'])) {
280 //Iterate on each location
281 foreach($locations as $location) {
282 //Found location
283 if ($location->getId() == $parameters['session']['location']['id']) {
284 //Set location as default
285 $locationDefault = $location;
286
287 //Stop search
288 break;
289 }
290 }
291 }
292
293 //Create ApplicationType form
294 $application = $this->factory->create('Rapsys\AirBundle\Form\ApplicationType', null, [
295 //Set the action
296 'action' => $this->generateUrl('rapsysair_application_add'),
297 //Set the form attribute
298 'attr' => [ 'class' => 'col' ],
299 //Set dance choices
300 'dance_choices' => $dances,
301 //Set dance default
302 'dance_default' => $danceDefault,
303 //Set dance favorites
304 'dance_favorites' => $danceFavorites,
305 //Set location choices
306 'location_choices' => $locations,
307 //Set location default
308 'location_default' => $locationDefault,
309 //Set location favorites
310 'location_favorites' => $locationFavorites,
311 //With user
312 'user' => $this->checker->isGranted('ROLE_ADMIN'),
313 //Set user choices
314 'user_choices' => $this->doctrine->getRepository(User::class)->findChoicesAsArray(),
315 //Set default user to current
316 'user_default' => $this->security->getUser()->getId(),
317 //Set to session slot or evening by default
318 //XXX: default to Evening (3)
319 'slot_default' => $this->doctrine->getRepository(Slot::class)->findOneById($parameters['session']['slot']['id']??3)
320 ]);
321
322 //Add form to context
323 $parameters['forms']['application'] = $application->createView();
324 }
325 }/*
326 #XXX: removed because it fucks up the seo by displaying register and login form instead of content
327 #XXX: until we find a better way, removed !!!
328 //Create login form for anonymous
329 elseif (!$this->checker->isGranted('IS_AUTHENTICATED_REMEMBERED')) {
330 //Create LoginType form
331 $login = $this->factory->create('Rapsys\UserBundle\Form\LoginType', null, [
332 //Set the action
333 'action' => $this->generateUrl('rapsysuser_login'),
334 //Disable password repeated
335 'password_repeated' => false,
336 //Set the form attribute
337 'attr' => [ 'class' => 'col' ]
338 ]);
339
340 //Add form to context
341 $parameters['forms']['login'] = $login->createView();
342
343 //Set field
344 $field = [
345 //With mail
346 'mail' => true,
347 //Without civility
348 'civility' => false,
349 //Without pseudonym
350 'pseudonym' => false,
351 //Without forename
352 'forename' => false,
353 //Without surname
354 'surname' => false,
355 //Without password
356 'password' => false,
357 //Without slug
358 'slug' => false,
359 //Without phone
360 'phone' => false
361 ];
362
363 //Create RegisterType form
364 $register = $this->factory->create('Rapsys\AirBundle\Form\RegisterType', null, $field+[
365 //Set the action
366 'action' => $this->generateUrl(
367 'rapsysuser_register',
368 [
369 'mail' => $smail = $this->slugger->short(''),
370 'field' => $sfield = $this->slugger->serialize($field),
371 'hash' => $this->slugger->hash($smail.$sfield)
372 ]
373 ),
374 //Set the form attribute
375 'attr' => [ 'class' => 'col' ]
376 ]);
377
378 //Add form to context
379 $parameters['forms']['register'] = $register->createView();
380 }*/
381
382 //Without alternates
383 if (count($parameters['alternates']) <= 1) {
384 //Set routeParams
385 $routeParams = $this->routeParams;
386
387 //Iterate on locales excluding current one
388 foreach($this->config['locales'] as $locale) {
389 //With current locale
390 if ($locale !== $this->locale) {
391 //Set titles
392 $titles = [];
393
394 //Set route params locale
395 $routeParams['_locale'] = $locale;
396
397 //Iterate on other locales
398 foreach(array_diff($this->config['locales'], [$locale]) as $other) {
399 //Set other locale title
400 $titles[$other] = $this->translator->trans($this->config['languages'][$locale], [], null, $other);
401 }
402
403 //Set locale locales context
404 $parameters['alternates'][str_replace('_', '-', $locale)] = [
405 'absolute' => $this->router->generate($this->route, $routeParams, UrlGeneratorInterface::ABSOLUTE_URL),
406 'relative' => $this->router->generate($this->route, $routeParams),
407 'title' => implode('/', $titles),
408 'translated' => $this->translator->trans($this->config['languages'][$locale], [], null, $locale)
409 ];
410
411 //Add shorter locale
412 if (empty($parameters['alternates'][$shortCurrent = substr($locale, 0, 2)])) {
413 //Set locale locales context
414 $parameters['alternates'][$shortCurrent] = $parameters['alternates'][str_replace('_', '-', $locale)];
415 }
416 }
417 }
418 }
419
420 //With page infos and without facebook texts
421 if (count($parameters['fbimage']) <= 1 && isset($parameters['title']) && isset($this->route) && isset($this->routeParams)) {
422 //Append facebook image texts
423 $parameters['fbimage'] += [
424 'texts' => [
425 $parameters['title']['page'] => [
426 'font' => 'irishgrover',
427 'align' => 'left'
428 ]/*XXX: same problem as url, too long :'(,
429 $parameters['description'] => [
430 'align' => 'right',
431 'canonical' => true,
432 'font' => 'labelleaurore',
433 'size' => 50
434 ]*/
435 ]
436 ];
437
438 /*With short path info
439 We don't add this stupid url in image !!!
440 if (strlen($pathInfo = $this->router->generate($this->route, $this->routeParams)) <= 64) {
441 => [
442 'align' => 'right',
443 'canonical' => true,
444 'font' => 'labelleaurore',
445 'size' => 50
446 ]
447 }*/
448 }
449
450 //With empty locations link
451 if (empty($parameters['locations_link'])) {
452 //Set locations link
453 $parameters['locations_link'] = $this->router->generate('rapsysair_location');
454 }
455
456 //With empty locations title
457 if (empty($parameters['locations_title'])) {
458 //Set locations title
459 $parameters['locations_title'] = $this->translator->trans('Locations', [], null, $this->locale);
460 }
461
462 //With canonical
463 if (!empty($parameters['canonical'])) {
464 //Set facebook url
465 $parameters['facebook']['og:url'] = $parameters['canonical'];
466 }
467
468 //With empty facebook title and title
469 if (empty($parameters['facebook']['og:title']) && !empty($parameters['title'])) {
470 //Set facebook title
471 $parameters['facebook']['og:title'] = $parameters['title'];
472 }
473
474 //With empty facebook description and description
475 if (empty($parameters['facebook']['og:description']) && !empty($parameters['description'])) {
476 //Set facebook description
477 $parameters['facebook']['og:description'] = $parameters['description'];
478 }
479
480 //With locale
481 if (!empty($this->locale)) {
482 //Set facebook locale
483 $parameters['facebook']['og:locale'] = $this->locale;
484
485 //With alternates
486 //XXX: locale change when fb_locale=xx_xx is provided is done in FacebookSubscriber
487 //XXX: see https://stackoverflow.com/questions/20827882/in-open-graph-markup-whats-the-use-of-oglocalealternate-without-the-locati
488 if (!empty($parameters['alternates'])) {
489 //Iterate on alternates
490 foreach($parameters['alternates'] as $lang => $alternate) {
491 if (strlen($lang) == 5) {
492 //Set facebook locale alternate
493 $parameters['facebook']['og:locale:alternate'] = str_replace('-', '_', $lang);
494 }
495 }
496 }
497 }
498
499 //Without facebook image defined and texts
500 if (empty($parameters['facebook']['og:image']) && !empty($this->request) && !empty($parameters['fbimage']['texts']) && !empty($this->modified)) {
501 //Get facebook image
502 $parameters['facebook'] += $this->image->getFacebook($this->request->getPathInfo(), $parameters['fbimage']['texts'], $this->modified->getTimestamp());
503 }
504
505 //Call twig render method
506 $content = $this->twig->render($view, $parameters);
507
508 //Invalidate OK response on invalid form
509 if (200 === $response->getStatusCode()) {
510 foreach ($parameters as $v) {
511 if ($v instanceof FormInterface && $v->isSubmitted() && !$v->isValid()) {
512 $response->setStatusCode(422);
513 break;
514 }
515 }
516 }
517
518 //Store content in response
519 $response->setContent($content);
520
521 //Return response
522 return $response;
523 }
524
525 /**
526 * {@inheritdoc}
527 *
528 * @see vendor/symfony/framework-bundle/Controller/AbstractController.php
529 */
530 public static function getSubscribedServices(): array {
531 //Return subscribed services
532 return [
533 'doctrine' => ManagerRegistry::class,
534 'doctrine.orm.default_entity_manager' => EntityManagerInterface::class,
535 'form.factory' => FormFactoryInterface::class,
536 'mailer.mailer' => MailerInterface::class,
537 'rapsysair.facebook_util' => FacebookUtil::class,
538 'rapsyspack.image_util' => ImageUtil::class,
539 'rapsyspack.path_package' => PackageInterface::class,
540 'rapsyspack.slugger_util' => SluggerUtil::class,
541 'rapsysuser.access_decision_manager' => AccessDecisionManagerInterface::class,
542 'request_stack' => RequestStack::class,
543 'router' => RouterInterface::class,
544 'security.authorization_checker' => AuthorizationCheckerInterface::class,
545 'service_container' => ContainerInterface::class,
546 'translator' => TranslatorInterface::class
547 ];
548 }
549 }