1 <?php
declare(strict_types
=1);
4 * This file is part of the Rapsys AirBundle package.
6 * (c) Raphaël Gertz <symfony@rapsys.eu>
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
12 namespace Rapsys\AirBundle\Controller
;
14 use Doctrine\ORM\EntityManagerInterface
;
15 use Doctrine\Persistence\ManagerRegistry
;
17 use Psr\Container\ContainerInterface
;
18 use Psr\Log\LoggerInterface
;
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
;
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
;
45 use Rapsys\PackBundle\Util\FacebookUtil
;
46 use Rapsys\PackBundle\Util\ImageUtil
;
47 use Rapsys\PackBundle\Util\SluggerUtil
;
50 * Provides common features needed in controllers.
54 abstract class AbstractController
extends BaseAbstractController
implements ServiceSubscriberInterface
{
58 protected array $config;
63 protected array $context;
68 protected string $locale;
73 protected \DateTimeImmutable
$modified;
78 protected \DatePeriod
$period;
83 protected Request
$request;
88 protected string $route;
93 protected array $routeParams;
96 * Abstract constructor
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
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
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) {
120 $this->config
= $container->getParameter(RapsysAirBundle
::getAlias());
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')
134 $this->request
= $this->stack
->getMainRequest();
137 $this->locale
= $this->request
->getLocale();
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');
152 $this->routeParams
= $this->request
->attributes
->get('_route_params');
154 //With route and routeParams
155 if ($this->route
!== null && $this->routeParams
!== null) {
157 $canonical = $this->router
->generate($this->route
, $this->routeParams
, UrlGeneratorInterface
::ABSOLUTE_URL
);
161 substr($this->locale
, 0, 2) => [
162 'absolute' => $canonical
169 'alternates' => $alternates,
170 'canonical' => $canonical,
172 'address' => $this->config
['contact']['address'],
173 'name' => $this->translator
->trans($this->config
['contact']['name'])
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']
182 'description' => null,
183 'donate' => $this->config
['donate'],
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']
191 //XXX: TODO: only generate it when fb robot request the url ???
195 'font' => 'irishgrover',
200 'icon' => $this->config
['icon'],
202 'locale' => str_replace('_', '-', $this->locale
),
203 'logo' => $this->config
['logo'],
205 'root' => $this->router
->generate($this->config
['root']),
219 protected function render(string $view, array $parameters = [], ?Response
$response = null): Response
{
220 //Create response when null
221 $response ??= new Response();
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());
231 $danceDefault = !empty($danceFavorites)?current($danceFavorites):null;
233 //Get favorites locations
234 $locationFavorites = $this->doctrine
->getRepository(Location
::class)->findByUserId($this->security
->getUser()->getId());
236 //Set location default
237 $locationDefault = !empty($locationFavorites)?current($locationFavorites):null;
240 if ($this->checker
->isGranted('ROLE_ADMIN')) {
242 $dances = $this->doctrine
->getRepository(Dance
::class)->findAll();
245 $locations = $this->doctrine
->getRepository(Location
::class)->findAll();
248 //Restrict to favorite dances
249 $dances = $danceFavorites;
252 $danceFavorites = [];
254 //Restrict to favorite locations
255 $locations = $locationFavorites;
258 $locationFavorites = [];
261 //With session application dance id
262 if (!empty($parameters['session']['application']['dance']['id'])) {
263 //Iterate on each dance
264 foreach($dances as $dance) {
266 if ($dance->getId() == $parameters['session']['application']['dance']['id']) {
267 //Set dance as default
268 $danceDefault = $dance;
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) {
283 if ($location->getId() == $parameters['session']['location']['id']) {
284 //Set location as default
285 $locationDefault = $location;
293 //Create ApplicationType form
294 $application = $this->factory
->create('Rapsys\AirBundle\Form\ApplicationType', null, [
296 'action' => $this->generateUrl('rapsysair_application_add'),
297 //Set the form attribute
298 'attr' => [ 'class' => 'col' ],
300 'dance_choices' => $dances,
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,
312 'user' => $this->checker
->isGranted('ROLE_ADMIN'),
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)
322 //Add form to context
323 $parameters['forms']['application'] = $application->createView();
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, [
333 'action' => $this->generateUrl('rapsysuser_login'),
334 //Disable password repeated
335 'password_repeated' => false,
336 //Set the form attribute
337 'attr' => [ 'class' => 'col' ]
340 //Add form to context
341 $parameters['forms']['login'] = $login->createView();
350 'pseudonym' => false,
363 //Create RegisterType form
364 $register = $this->factory->create('Rapsys\AirBundle\Form\RegisterType', null, $field+[
366 'action' => $this->generateUrl(
367 'rapsysuser_register',
369 'mail' => $smail = $this->slugger->short(''),
370 'field' => $sfield = $this->slugger->serialize($field),
371 'hash' => $this->slugger->hash($smail.$sfield)
374 //Set the form attribute
375 'attr' => [ 'class' => 'col' ]
378 //Add form to context
379 $parameters['forms']['register'] = $register->createView();
383 if (count($parameters['alternates']) <= 1) {
385 $routeParams = $this->routeParams
;
387 //Iterate on locales excluding current one
388 foreach($this->config
['locales'] as $locale) {
389 //With current locale
390 if ($locale !== $this->locale
) {
394 //Set route params locale
395 $routeParams['_locale'] = $locale;
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);
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)
412 if (empty($parameters['alternates'][$shortCurrent = substr($locale, 0, 2)])) {
413 //Set locale locales context
414 $parameters['alternates'][$shortCurrent] = $parameters['alternates'][str_replace('_', '-', $locale)];
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'] +
= [
425 $parameters['title']['page'] => [
426 'font' => 'irishgrover',
428 ]/*XXX: same problem as url, too long :'(,
429 $parameters['description'] => [
432 'font' => 'labelleaurore',
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) {
444 'font' => 'labelleaurore',
450 //With empty locations link
451 if (empty($parameters['locations_link'])) {
453 $parameters['locations_link'] = $this->router
->generate('rapsysair_location');
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
);
463 if (!empty($parameters['canonical'])) {
465 $parameters['facebook']['og:url'] = $parameters['canonical'];
468 //With empty facebook title and title
469 if (empty($parameters['facebook']['og:title']) && !empty($parameters['title'])) {
471 $parameters['facebook']['og:title'] = $parameters['title'];
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'];
481 if (!empty($this->locale
)) {
482 //Set facebook locale
483 $parameters['facebook']['og:locale'] = $this->locale
;
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);
499 //Without facebook image defined and texts
500 if (empty($parameters['facebook']['og:image']) && !empty($this->request
) && !empty($parameters['fbimage']['texts']) && !empty($this->modified
)) {
502 $parameters['facebook'] +
= $this->image
->getFacebook($this->request
->getPathInfo(), $parameters['fbimage']['texts'], $this->modified
->getTimestamp());
505 //Call twig render method
506 $content = $this->twig
->render($view, $parameters);
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);
518 //Store content in response
519 $response->setContent($content);
528 * @see vendor/symfony/framework-bundle/Controller/AbstractController.php
530 public static function getSubscribedServices(): array {
531 //Return subscribed services
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