vendor/symfony/framework-bundle/Controller/AbstractController.php line 288

Open in your IDE?
  1. <?php
  2. /*
  3.  * This file is part of the Symfony package.
  4.  *
  5.  * (c) Fabien Potencier <fabien@symfony.com>
  6.  *
  7.  * For the full copyright and license information, please view the LICENSE
  8.  * file that was distributed with this source code.
  9.  */
  10. namespace Symfony\Bundle\FrameworkBundle\Controller;
  11. use App\Entity\Uid;
  12. use App\Model\Profil;
  13. use Twig\Environment;
  14. use Psr\Link\LinkInterface;
  15. use App\Entity\ProfilAmenageur;
  16. use Symfony\Component\Form\FormView;
  17. use Psr\Container\ContainerInterface;
  18. use App\Repository\ProfilMoRepository;
  19. use Doctrine\ORM\EntityManagerInterface;
  20. use Doctrine\Persistence\ManagerRegistry;
  21. use Symfony\Component\Form\FormInterface;
  22. use Symfony\Component\Messenger\Envelope;
  23. use App\Repository\NotificationRepository;
  24. use App\Repository\ProfilAmenageurRepository;
  25. use Symfony\Component\HttpFoundation\Request;
  26. use Symfony\Component\Security\Core\Security;
  27. use Symfony\Component\HttpFoundation\Response;
  28. use Symfony\Component\Routing\RouterInterface;
  29. use Symfony\Component\Security\Csrf\CsrfToken;
  30. use App\Repository\ProfilInstructeurRepository;
  31. use App\Repository\ProfilConstructeurRepository;
  32. use Symfony\Component\Form\FormBuilderInterface;
  33. use Symfony\Component\Form\FormFactoryInterface;
  34. use Symfony\Component\HttpFoundation\JsonResponse;
  35. use Symfony\Component\HttpFoundation\RequestStack;
  36. use Symfony\Component\WebLink\GenericLinkProvider;
  37. use Symfony\Component\Messenger\MessageBusInterface;
  38. use Symfony\Component\HttpKernel\HttpKernelInterface;
  39. use Symfony\Component\Serializer\SerializerInterface;
  40. use Symfony\Component\HttpFoundation\RedirectResponse;
  41. use Symfony\Component\HttpFoundation\StreamedResponse;
  42. use Symfony\Component\HttpFoundation\ResponseHeaderBag;
  43. use Symfony\Component\Security\Core\User\UserInterface;
  44. use Symfony\Component\Form\Extension\Core\Type\FormType;
  45. use Symfony\Component\HttpFoundation\BinaryFileResponse;
  46. use Symfony\Contracts\Service\ServiceSubscriberInterface;
  47. use Symfony\Component\HttpFoundation\Session\SessionInterface;
  48. use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
  49. use Symfony\Component\Security\Csrf\CsrfTokenManagerInterface;
  50. use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
  51. use Symfony\Component\WebLink\EventListener\AddLinkHeaderListener;
  52. use Symfony\Component\Security\Core\Exception\AccessDeniedException;
  53. use Symfony\Component\HttpFoundation\Exception\SessionNotFoundException;
  54. use Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException;
  55. use Symfony\Component\DependencyInjection\ParameterBag\ContainerBagInterface;
  56. use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
  57. use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
  58. /**
  59.  * Provides shortcuts for HTTP-related features in controllers.
  60.  *
  61.  * @author Fabien Potencier <fabien@symfony.com>
  62.  */
  63. abstract class AbstractController implements ServiceSubscriberInterface
  64. {
  65.     /**
  66.      * @var ContainerInterface
  67.      */
  68.     protected $container;
  69.     protected $manager;
  70.     protected $registry;
  71.     protected $notificationRepository;
  72.     public function __construct(EntityManagerInterface $emManagerRegistry $registryNotificationRepository $notificationRepository null)
  73.     {
  74.         $this->manager $em;
  75.         $this->registry $registry;
  76.         $this->notificationRepository $notificationRepository;
  77.     }
  78.     /**
  79.      * @required
  80.      */
  81.     public function setContainer(ContainerInterface $container): ?ContainerInterface
  82.     {
  83.         $previous $this->container;
  84.         $this->container $container;
  85.         return $previous;
  86.     }
  87.     /**
  88.      * Gets a container parameter by its name.
  89.      *
  90.      * @return array|bool|float|int|string|null
  91.      */
  92.     protected function getParameter(string $name)
  93.     {
  94.         if (!$this->container->has('parameter_bag')) {
  95.             throw new ServiceNotFoundException('parameter_bag.'nullnull, [], sprintf('The "%s::getParameter()" method is missing a parameter bag to work properly. Did you forget to register your controller as a service subscriber? This can be fixed either by using autoconfiguration or by manually wiring a "parameter_bag" in the service locator passed to the controller.', static::class));
  96.         }
  97.         return $this->container->get('parameter_bag')->get($name);
  98.     }
  99.     public static function getSubscribedServices()
  100.     {
  101.         return [
  102.             'router' => '?'.RouterInterface::class,
  103.             'request_stack' => '?'.RequestStack::class,
  104.             'http_kernel' => '?'.HttpKernelInterface::class,
  105.             'serializer' => '?'.SerializerInterface::class,
  106.             'session' => '?'.SessionInterface::class,
  107.             'security.authorization_checker' => '?'.AuthorizationCheckerInterface::class,
  108.             'twig' => '?'.Environment::class,
  109.             'doctrine' => '?'.ManagerRegistry::class, // to be removed in 6.0
  110.             'form.factory' => '?'.FormFactoryInterface::class,
  111.             'security.token_storage' => '?'.TokenStorageInterface::class,
  112.             'security.csrf.token_manager' => '?'.CsrfTokenManagerInterface::class,
  113.             'parameter_bag' => '?'.ContainerBagInterface::class,
  114.             'message_bus' => '?'.MessageBusInterface::class, // to be removed in 6.0
  115.             'messenger.default_bus' => '?'.MessageBusInterface::class, // to be removed in 6.0
  116.         ];
  117.     }
  118.     /**
  119.      * Returns true if the service id is defined.
  120.      *
  121.      * @deprecated since Symfony 5.4, use method or constructor injection in your controller instead
  122.      */
  123.     protected function has(string $id): bool
  124.     {
  125.         trigger_deprecation('symfony/framework-bundle''5.4''Method "%s()" is deprecated, use method or constructor injection in your controller instead.'__METHOD__);
  126.         return $this->container->has($id);
  127.     }
  128.     /**
  129.      * Gets a container service by its id.
  130.      *
  131.      * @return object The service
  132.      *
  133.      * @deprecated since Symfony 5.4, use method or constructor injection in your controller instead
  134.      */
  135.     protected function get(string $id): object
  136.     {
  137.         trigger_deprecation('symfony/framework-bundle''5.4''Method "%s()" is deprecated, use method or constructor injection in your controller instead.'__METHOD__);
  138.         return $this->container->get($id);
  139.     }
  140.     /**
  141.      * Generates a URL from the given parameters.
  142.      *
  143.      * @see UrlGeneratorInterface
  144.      */
  145.     protected function generateUrl(string $route, array $parameters = [], int $referenceType UrlGeneratorInterface::ABSOLUTE_PATH): string
  146.     {
  147.         return $this->container->get('router')->generate($route$parameters$referenceType);
  148.     }
  149.     /**
  150.      * Forwards the request to another controller.
  151.      *
  152.      * @param string $controller The controller name (a string like Bundle\BlogBundle\Controller\PostController::indexAction)
  153.      */
  154.     protected function forward(string $controller, array $path = [], array $query = []): Response
  155.     {
  156.         $request $this->container->get('request_stack')->getCurrentRequest();
  157.         $path['_controller'] = $controller;
  158.         $subRequest $request->duplicate($querynull$path);
  159.         return $this->container->get('http_kernel')->handle($subRequestHttpKernelInterface::SUB_REQUEST);
  160.     }
  161.     /**
  162.      * Returns a RedirectResponse to the given URL.
  163.      */
  164.     protected function redirect(string $urlint $status 302): RedirectResponse
  165.     {
  166.         return new RedirectResponse($url$status);
  167.     }
  168.     /**
  169.      * Returns a RedirectResponse to the given route with the given parameters.
  170.      */
  171.     protected function redirectToRoute(string $route, array $parameters = [], int $status 302): RedirectResponse
  172.     {
  173.         return $this->redirect($this->generateUrl($route$parameters), $status);
  174.     }
  175.     /**
  176.      * Returns a JsonResponse that uses the serializer component if enabled, or json_encode.
  177.      */
  178.     protected function json($dataint $status 200, array $headers = [], array $context = []): JsonResponse
  179.     {
  180.         if ($this->container->has('serializer')) {
  181.             $json $this->container->get('serializer')->serialize($data'json'array_merge([
  182.                 'json_encode_options' => JsonResponse::DEFAULT_ENCODING_OPTIONS,
  183.             ], $context));
  184.             return new JsonResponse($json$status$headerstrue);
  185.         }
  186.         return new JsonResponse($data$status$headers);
  187.     }
  188.     /**
  189.      * Returns a BinaryFileResponse object with original or customized file name and disposition header.
  190.      *
  191.      * @param \SplFileInfo|string $file File object or path to file to be sent as response
  192.      */
  193.     protected function file($filestring $fileName nullstring $disposition ResponseHeaderBag::DISPOSITION_ATTACHMENT): BinaryFileResponse
  194.     {
  195.         $response = new BinaryFileResponse($file);
  196.         $response->setContentDisposition($dispositionnull === $fileName $response->getFile()->getFilename() : $fileName);
  197.         return $response;
  198.     }
  199.     /**
  200.      * Adds a flash message to the current session for type.
  201.      *
  202.      * @throws \LogicException
  203.      */
  204.     protected function addFlash(string $type$message): void
  205.     {
  206.         try {
  207.             $this->container->get('request_stack')->getSession()->getFlashBag()->add($type$message);
  208.         } catch (SessionNotFoundException $e) {
  209.             throw new \LogicException('You cannot use the addFlash method if sessions are disabled. Enable them in "config/packages/framework.yaml".'0$e);
  210.         }
  211.     }
  212.     /**
  213.      * Checks if the attribute is granted against the current authentication token and optionally supplied subject.
  214.      *
  215.      * @throws \LogicException
  216.      */
  217.     protected function isGranted($attribute$subject null): bool
  218.     {
  219.         if (!$this->container->has('security.authorization_checker')) {
  220.             throw new \LogicException('The SecurityBundle is not registered in your application. Try running "composer require symfony/security-bundle".');
  221.         }
  222.         return $this->container->get('security.authorization_checker')->isGranted($attribute$subject);
  223.     }
  224.     /**
  225.      * Throws an exception unless the attribute is granted against the current authentication token and optionally
  226.      * supplied subject.
  227.      *
  228.      * @throws AccessDeniedException
  229.      */
  230.     protected function denyAccessUnlessGranted($attribute$subject nullstring $message 'Access Denied.'): void
  231.     {
  232.         if (!$this->isGranted($attribute$subject)) {
  233.             $exception $this->createAccessDeniedException($message);
  234.             $exception->setAttributes($attribute);
  235.             $exception->setSubject($subject);
  236.             throw $exception;
  237.         }
  238.     }
  239.     /**
  240.      * Returns a rendered view.
  241.      */
  242.     protected function renderView(string $view, array $parameters = []): string
  243.     {
  244.         if (!$this->container->has('twig')) {
  245.             throw new \LogicException('You cannot use the "renderView" method if the Twig Bundle is not available. Try running "composer require symfony/twig-bundle".');
  246.         }
  247.         return $this->container->get('twig')->render($view$parameters);
  248.     }
  249.     /**
  250.      * Renders a view.
  251.      */
  252.     protected function render(string $view, array $parameters = [], Response $response null): Response
  253.     {
  254.         $content $this->renderView($view$parameters);
  255.         if (null === $response) {
  256.             $response = new Response();
  257.         }
  258.         $response->setContent($content);
  259.         return $response;
  260.     }
  261.     /**
  262.      * Renders a view and sets the appropriate status code when a form is listed in parameters.
  263.      *
  264.      * If an invalid form is found in the list of parameters, a 422 status code is returned.
  265.      */
  266.     protected function renderForm(string $view, array $parameters = [], Response $response null): Response
  267.     {
  268.         if (null === $response) {
  269.             $response = new Response();
  270.         }
  271.         foreach ($parameters as $k => $v) {
  272.             if ($v instanceof FormView) {
  273.                 throw new \LogicException(sprintf('Passing a FormView to "%s::renderForm()" is not supported, pass directly the form instead for parameter "%s".'get_debug_type($this), $k));
  274.             }
  275.             if (!$v instanceof FormInterface) {
  276.                 continue;
  277.             }
  278.             $parameters[$k] = $v->createView();
  279.             if (200 === $response->getStatusCode() && $v->isSubmitted() && !$v->isValid()) {
  280.                 $response->setStatusCode(422);
  281.             }
  282.         }
  283.         return $this->render($view$parameters$response);
  284.     }
  285.     /**
  286.      * Streams a view.
  287.      */
  288.     protected function stream(string $view, array $parameters = [], StreamedResponse $response null): StreamedResponse
  289.     {
  290.         if (!$this->container->has('twig')) {
  291.             throw new \LogicException('You cannot use the "stream" method if the Twig Bundle is not available. Try running "composer require symfony/twig-bundle".');
  292.         }
  293.         $twig $this->container->get('twig');
  294.         $callback = function () use ($twig$view$parameters) {
  295.             $twig->display($view$parameters);
  296.         };
  297.         if (null === $response) {
  298.             return new StreamedResponse($callback);
  299.         }
  300.         $response->setCallback($callback);
  301.         return $response;
  302.     }
  303.     /**
  304.      * Returns a NotFoundHttpException.
  305.      *
  306.      * This will result in a 404 response code. Usage example:
  307.      *
  308.      *     throw $this->createNotFoundException('Page not found!');
  309.      */
  310.     protected function createNotFoundException(string $message 'Not Found', \Throwable $previous null): NotFoundHttpException
  311.     {
  312.         return new NotFoundHttpException($message$previous);
  313.     }
  314.     /**
  315.      * Returns an AccessDeniedException.
  316.      *
  317.      * This will result in a 403 response code. Usage example:
  318.      *
  319.      *     throw $this->createAccessDeniedException('Unable to access this page!');
  320.      *
  321.      * @throws \LogicException If the Security component is not available
  322.      */
  323.     protected function createAccessDeniedException(string $message 'Access Denied.', \Throwable $previous null): AccessDeniedException
  324.     {
  325.         if (!class_exists(AccessDeniedException::class)) {
  326.             throw new \LogicException('You cannot use the "createAccessDeniedException" method if the Security component is not available. Try running "composer require symfony/security-bundle".');
  327.         }
  328.         return new AccessDeniedException($message$previous);
  329.     }
  330.     /**
  331.      * Creates and returns a Form instance from the type of the form.
  332.      */
  333.     protected function createForm(string $type$data null, array $options = []): FormInterface
  334.     {
  335.         return $this->container->get('form.factory')->create($type$data$options);
  336.     }
  337.     /**
  338.      * Creates and returns a form builder instance.
  339.      */
  340.     protected function createFormBuilder($data null, array $options = []): FormBuilderInterface
  341.     {
  342.         return $this->container->get('form.factory')->createBuilder(FormType::class, $data$options);
  343.     }
  344.     /**
  345.      * Shortcut to return the Doctrine Registry service.
  346.      *
  347.      * @throws \LogicException If DoctrineBundle is not available
  348.      *
  349.      * @deprecated since Symfony 5.4, inject an instance of ManagerRegistry in your controller instead
  350.      */
  351.     protected function getDoctrine(): ManagerRegistry
  352.     {
  353.         trigger_deprecation('symfony/framework-bundle''5.4''Method "%s()" is deprecated, inject an instance of ManagerRegistry in your controller instead.'__METHOD__);
  354.         if (!$this->container->has('doctrine')) {
  355.             throw new \LogicException('The DoctrineBundle is not registered in your application. Try running "composer require symfony/orm-pack".');
  356.         }
  357.         return $this->container->get('doctrine');
  358.     }
  359.     /**
  360.      * Get a user from the Security Token Storage.
  361.      *
  362.      * @return UserInterface|null
  363.      *
  364.      * @throws \LogicException If SecurityBundle is not available
  365.      *
  366.      * @see TokenInterface::getUser()
  367.      */
  368.     protected function getUser()
  369.     {
  370.         if (!$this->container->has('security.token_storage')) {
  371.             throw new \LogicException('The SecurityBundle is not registered in your application. Try running "composer require symfony/security-bundle".');
  372.         }
  373.         if (null === $token $this->container->get('security.token_storage')->getToken()) {
  374.             return null;
  375.         }
  376.         // @deprecated since 5.4, $user will always be a UserInterface instance
  377.         if (!\is_object($user $token->getUser())) {
  378.             // e.g. anonymous authentication
  379.             return null;
  380.         }
  381.         if($user->getProfil() == null){
  382.             $user->setProfil($this->registry);
  383.         }
  384.         
  385.         return $user;
  386.     }
  387.     /*protected function getProfil(ManagerRegistry $manager, $security = null)
  388.     {
  389.        
  390.         if ($security->getUser()->getRoles()[0] == "ROLE_AMENAGEUR") {
  391.             $repository = new ProfilAmenageurRepository($manager);
  392.         }
  393.         elseif ($security->getUser()->getRoles()[0] == "ROLE_INSTRUCTEUR") {
  394.             $repository = new ProfilInstructeurRepository($manager);
  395.         }
  396.         elseif ($security->getUser()->getRoles()[0] == "ROLE_CONSTRUCTEUR") {
  397.             $repository = new ProfilConstructeurRepository($manager);
  398.         }
  399.         elseif ($security->getUser()->getRoles()[0] == "ROLE_MO") {
  400.             $repository = new ProfilMoRepository($manager);
  401.         }
  402.         else {
  403.             return null;
  404.         }
  405.         
  406.         return $repository->findOneBy(["uid" => $security->getUser()]);
  407.     }*/
  408.     
  409.     /**
  410.      * Checks the validity of a CSRF token.
  411.      *
  412.      * @param string      $id    The id used when generating the token
  413.      * @param string|null $token The actual token sent with the request that should be validated
  414.      */
  415.     protected function isCsrfTokenValid(string $id, ?string $token): bool
  416.     {
  417.         if (!$this->container->has('security.csrf.token_manager')) {
  418.             throw new \LogicException('CSRF protection is not enabled in your application. Enable it with the "csrf_protection" key in "config/packages/framework.yaml".');
  419.         }
  420.         return $this->container->get('security.csrf.token_manager')->isTokenValid(new CsrfToken($id$token));
  421.     }
  422.     /**
  423.      * Dispatches a message to the bus.
  424.      *
  425.      * @param object|Envelope $message The message or the message pre-wrapped in an envelope
  426.      *
  427.      * @deprecated since Symfony 5.4, inject an instance of MessageBusInterface in your controller instead
  428.      */
  429.     protected function dispatchMessage(object $message, array $stamps = []): Envelope
  430.     {
  431.         trigger_deprecation('symfony/framework-bundle''5.4''Method "%s()" is deprecated, inject an instance of MessageBusInterface in your controller instead.'__METHOD__);
  432.         if (!$this->container->has('messenger.default_bus')) {
  433.             $message class_exists(Envelope::class) ? 'You need to define the "messenger.default_bus" configuration option.' 'Try running "composer require symfony/messenger".';
  434.             throw new \LogicException('The message bus is not enabled in your application. '.$message);
  435.         }
  436.         return $this->container->get('messenger.default_bus')->dispatch($message$stamps);
  437.     }
  438.     /**
  439.      * Adds a Link HTTP header to the current response.
  440.      *
  441.      * @see https://tools.ietf.org/html/rfc5988
  442.      */
  443.     protected function addLink(Request $requestLinkInterface $link): void
  444.     {
  445.         if (!class_exists(AddLinkHeaderListener::class)) {
  446.             throw new \LogicException('You cannot use the "addLink" method if the WebLink component is not available. Try running "composer require symfony/web-link".');
  447.         }
  448.         if (null === $linkProvider $request->attributes->get('_links')) {
  449.             $request->attributes->set('_links', new GenericLinkProvider([$link]));
  450.             return;
  451.         }
  452.         $request->attributes->set('_links'$linkProvider->withLink($link));
  453.     }
  454. }