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

  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 Psr\Container\ContainerInterface;
  12. use Psr\Link\EvolvableLinkInterface;
  13. use Psr\Link\LinkInterface;
  14. use Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException;
  15. use Symfony\Component\DependencyInjection\ParameterBag\ContainerBagInterface;
  16. use Symfony\Component\Form\Extension\Core\Type\FormType;
  17. use Symfony\Component\Form\FormBuilderInterface;
  18. use Symfony\Component\Form\FormFactoryInterface;
  19. use Symfony\Component\Form\FormInterface;
  20. use Symfony\Component\HttpFoundation\BinaryFileResponse;
  21. use Symfony\Component\HttpFoundation\Exception\SessionNotFoundException;
  22. use Symfony\Component\HttpFoundation\JsonResponse;
  23. use Symfony\Component\HttpFoundation\RedirectResponse;
  24. use Symfony\Component\HttpFoundation\Request;
  25. use Symfony\Component\HttpFoundation\RequestStack;
  26. use Symfony\Component\HttpFoundation\Response;
  27. use Symfony\Component\HttpFoundation\ResponseHeaderBag;
  28. use Symfony\Component\HttpFoundation\Session\FlashBagAwareSessionInterface;
  29. use Symfony\Component\HttpFoundation\StreamedResponse;
  30. use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
  31. use Symfony\Component\HttpKernel\HttpKernelInterface;
  32. use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
  33. use Symfony\Component\Routing\RouterInterface;
  34. use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
  35. use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
  36. use Symfony\Component\Security\Core\Exception\AccessDeniedException;
  37. use Symfony\Component\Security\Core\User\UserInterface;
  38. use Symfony\Component\Security\Csrf\CsrfToken;
  39. use Symfony\Component\Security\Csrf\CsrfTokenManagerInterface;
  40. use Symfony\Component\Serializer\SerializerInterface;
  41. use Symfony\Component\WebLink\EventListener\AddLinkHeaderListener;
  42. use Symfony\Component\WebLink\GenericLinkProvider;
  43. use Symfony\Component\WebLink\HttpHeaderSerializer;
  44. use Symfony\Component\WebLink\Link;
  45. use Symfony\Contracts\Service\Attribute\Required;
  46. use Symfony\Contracts\Service\ServiceSubscriberInterface;
  47. use Twig\Environment;
  48. /**
  49.  * Provides shortcuts for HTTP-related features in controllers.
  50.  *
  51.  * @author Fabien Potencier <fabien@symfony.com>
  52.  */
  53. abstract class AbstractController implements ServiceSubscriberInterface
  54. {
  55.     /**
  56.      * @var ContainerInterface
  57.      */
  58.     protected $container;
  59.     #[Required]
  60.     public function setContainer(ContainerInterface $container): ?ContainerInterface
  61.     {
  62.         $previous $this->container;
  63.         $this->container $container;
  64.         return $previous;
  65.     }
  66.     /**
  67.      * Gets a container parameter by its name.
  68.      */
  69.     protected function getParameter(string $name): array|bool|string|int|float|\UnitEnum|null
  70.     {
  71.         if (!$this->container->has('parameter_bag')) {
  72.             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));
  73.         }
  74.         return $this->container->get('parameter_bag')->get($name);
  75.     }
  76.     public static function getSubscribedServices(): array
  77.     {
  78.         return [
  79.             'router' => '?'.RouterInterface::class,
  80.             'request_stack' => '?'.RequestStack::class,
  81.             'http_kernel' => '?'.HttpKernelInterface::class,
  82.             'serializer' => '?'.SerializerInterface::class,
  83.             'security.authorization_checker' => '?'.AuthorizationCheckerInterface::class,
  84.             'twig' => '?'.Environment::class,
  85.             'form.factory' => '?'.FormFactoryInterface::class,
  86.             'security.token_storage' => '?'.TokenStorageInterface::class,
  87.             'security.csrf.token_manager' => '?'.CsrfTokenManagerInterface::class,
  88.             'parameter_bag' => '?'.ContainerBagInterface::class,
  89.             'web_link.http_header_serializer' => '?'.HttpHeaderSerializer::class,
  90.         ];
  91.     }
  92.     /**
  93.      * Generates a URL from the given parameters.
  94.      *
  95.      * @see UrlGeneratorInterface
  96.      */
  97.     protected function generateUrl(string $route, array $parameters = [], int $referenceType UrlGeneratorInterface::ABSOLUTE_PATH): string
  98.     {
  99.         return $this->container->get('router')->generate($route$parameters$referenceType);
  100.     }
  101.     /**
  102.      * Forwards the request to another controller.
  103.      *
  104.      * @param string $controller The controller name (a string like "App\Controller\PostController::index" or "App\Controller\PostController" if it is invokable)
  105.      */
  106.     protected function forward(string $controller, array $path = [], array $query = []): Response
  107.     {
  108.         $request $this->container->get('request_stack')->getCurrentRequest();
  109.         $path['_controller'] = $controller;
  110.         $subRequest $request->duplicate($querynull$path);
  111.         return $this->container->get('http_kernel')->handle($subRequestHttpKernelInterface::SUB_REQUEST);
  112.     }
  113.     /**
  114.      * Returns a RedirectResponse to the given URL.
  115.      *
  116.      * @param int $status The HTTP status code (302 "Found" by default)
  117.      */
  118.     protected function redirect(string $urlint $status 302): RedirectResponse
  119.     {
  120.         return new RedirectResponse($url$status);
  121.     }
  122.     /**
  123.      * Returns a RedirectResponse to the given route with the given parameters.
  124.      *
  125.      * @param int $status The HTTP status code (302 "Found" by default)
  126.      */
  127.     protected function redirectToRoute(string $route, array $parameters = [], int $status 302): RedirectResponse
  128.     {
  129.         return $this->redirect($this->generateUrl($route$parameters), $status);
  130.     }
  131.     /**
  132.      * Returns a JsonResponse that uses the serializer component if enabled, or json_encode.
  133.      *
  134.      * @param int $status The HTTP status code (200 "OK" by default)
  135.      */
  136.     protected function json(mixed $dataint $status 200, array $headers = [], array $context = []): JsonResponse
  137.     {
  138.         if ($this->container->has('serializer')) {
  139.             $json $this->container->get('serializer')->serialize($data'json'array_merge([
  140.                 'json_encode_options' => JsonResponse::DEFAULT_ENCODING_OPTIONS,
  141.             ], $context));
  142.             return new JsonResponse($json$status$headerstrue);
  143.         }
  144.         return new JsonResponse($data$status$headers);
  145.     }
  146.     /**
  147.      * Returns a BinaryFileResponse object with original or customized file name and disposition header.
  148.      */
  149.     protected function file(\SplFileInfo|string $file, ?string $fileName nullstring $disposition ResponseHeaderBag::DISPOSITION_ATTACHMENT): BinaryFileResponse
  150.     {
  151.         $response = new BinaryFileResponse($file);
  152.         $response->setContentDisposition($disposition$fileName ?? $response->getFile()->getFilename());
  153.         return $response;
  154.     }
  155.     /**
  156.      * Adds a flash message to the current session for type.
  157.      *
  158.      * @throws \LogicException
  159.      */
  160.     protected function addFlash(string $typemixed $message): void
  161.     {
  162.         try {
  163.             $session $this->container->get('request_stack')->getSession();
  164.         } catch (SessionNotFoundException $e) {
  165.             throw new \LogicException('You cannot use the addFlash method if sessions are disabled. Enable them in "config/packages/framework.yaml".'0$e);
  166.         }
  167.         if (!$session instanceof FlashBagAwareSessionInterface) {
  168.             trigger_deprecation('symfony/framework-bundle''6.2''Calling "addFlash()" method when the session does not implement %s is deprecated.'FlashBagAwareSessionInterface::class);
  169.         }
  170.         $session->getFlashBag()->add($type$message);
  171.     }
  172.     /**
  173.      * Checks if the attribute is granted against the current authentication token and optionally supplied subject.
  174.      *
  175.      * @throws \LogicException
  176.      */
  177.     protected function isGranted(mixed $attributemixed $subject null): bool
  178.     {
  179.         if (!$this->container->has('security.authorization_checker')) {
  180.             throw new \LogicException('The SecurityBundle is not registered in your application. Try running "composer require symfony/security-bundle".');
  181.         }
  182.         return $this->container->get('security.authorization_checker')->isGranted($attribute$subject);
  183.     }
  184.     /**
  185.      * Throws an exception unless the attribute is granted against the current authentication token and optionally
  186.      * supplied subject.
  187.      *
  188.      * @throws AccessDeniedException
  189.      */
  190.     protected function denyAccessUnlessGranted(mixed $attributemixed $subject nullstring $message 'Access Denied.'): void
  191.     {
  192.         if (!$this->isGranted($attribute$subject)) {
  193.             $exception $this->createAccessDeniedException($message);
  194.             $exception->setAttributes([$attribute]);
  195.             $exception->setSubject($subject);
  196.             throw $exception;
  197.         }
  198.     }
  199.     /**
  200.      * Returns a rendered view.
  201.      *
  202.      * Forms found in parameters are auto-cast to form views.
  203.      */
  204.     protected function renderView(string $view, array $parameters = []): string
  205.     {
  206.         if (!$this->container->has('twig')) {
  207.             throw new \LogicException('You cannot use the "renderView" method if the Twig Bundle is not available. Try running "composer require symfony/twig-bundle".');
  208.         }
  209.         foreach ($parameters as $k => $v) {
  210.             if ($v instanceof FormInterface) {
  211.                 $parameters[$k] = $v->createView();
  212.             }
  213.         }
  214.         return $this->container->get('twig')->render($view$parameters);
  215.     }
  216.     /**
  217.      * Renders a view.
  218.      *
  219.      * If an invalid form is found in the list of parameters, a 422 status code is returned.
  220.      * Forms found in parameters are auto-cast to form views.
  221.      */
  222.     protected function render(string $view, array $parameters = [], ?Response $response null): Response
  223.     {
  224.         $content $this->renderView($view$parameters);
  225.         $response ??= new Response();
  226.         if (200 === $response->getStatusCode()) {
  227.             foreach ($parameters as $v) {
  228.                 if ($v instanceof FormInterface && $v->isSubmitted() && !$v->isValid()) {
  229.                     $response->setStatusCode(422);
  230.                     break;
  231.                 }
  232.             }
  233.         }
  234.         $response->setContent($content);
  235.         return $response;
  236.     }
  237.     /**
  238.      * Renders a view and sets the appropriate status code when a form is listed in parameters.
  239.      *
  240.      * If an invalid form is found in the list of parameters, a 422 status code is returned.
  241.      *
  242.      * @deprecated since Symfony 6.2, use render() instead
  243.      */
  244.     protected function renderForm(string $view, array $parameters = [], ?Response $response null): Response
  245.     {
  246.         trigger_deprecation('symfony/framework-bundle''6.2''The "%s::renderForm()" method is deprecated, use "render()" instead.'get_debug_type($this));
  247.         return $this->render($view$parameters$response);
  248.     }
  249.     /**
  250.      * Streams a view.
  251.      */
  252.     protected function stream(string $view, array $parameters = [], ?StreamedResponse $response null): StreamedResponse
  253.     {
  254.         if (!$this->container->has('twig')) {
  255.             throw new \LogicException('You cannot use the "stream" method if the Twig Bundle is not available. Try running "composer require symfony/twig-bundle".');
  256.         }
  257.         $twig $this->container->get('twig');
  258.         $callback = function () use ($twig$view$parameters) {
  259.             $twig->display($view$parameters);
  260.         };
  261.         if (null === $response) {
  262.             return new StreamedResponse($callback);
  263.         }
  264.         $response->setCallback($callback);
  265.         return $response;
  266.     }
  267.     /**
  268.      * Returns a NotFoundHttpException.
  269.      *
  270.      * This will result in a 404 response code. Usage example:
  271.      *
  272.      *     throw $this->createNotFoundException('Page not found!');
  273.      */
  274.     protected function createNotFoundException(string $message 'Not Found', ?\Throwable $previous null): NotFoundHttpException
  275.     {
  276.         return new NotFoundHttpException($message$previous);
  277.     }
  278.     /**
  279.      * Returns an AccessDeniedException.
  280.      *
  281.      * This will result in a 403 response code. Usage example:
  282.      *
  283.      *     throw $this->createAccessDeniedException('Unable to access this page!');
  284.      *
  285.      * @throws \LogicException If the Security component is not available
  286.      */
  287.     protected function createAccessDeniedException(string $message 'Access Denied.', ?\Throwable $previous null): AccessDeniedException
  288.     {
  289.         if (!class_exists(AccessDeniedException::class)) {
  290.             throw new \LogicException('You cannot use the "createAccessDeniedException" method if the Security component is not available. Try running "composer require symfony/security-bundle".');
  291.         }
  292.         return new AccessDeniedException($message$previous);
  293.     }
  294.     /**
  295.      * Creates and returns a Form instance from the type of the form.
  296.      */
  297.     protected function createForm(string $typemixed $data null, array $options = []): FormInterface
  298.     {
  299.         return $this->container->get('form.factory')->create($type$data$options);
  300.     }
  301.     /**
  302.      * Creates and returns a form builder instance.
  303.      */
  304.     protected function createFormBuilder(mixed $data null, array $options = []): FormBuilderInterface
  305.     {
  306.         return $this->container->get('form.factory')->createBuilder(FormType::class, $data$options);
  307.     }
  308.     /**
  309.      * Get a user from the Security Token Storage.
  310.      *
  311.      * @throws \LogicException If SecurityBundle is not available
  312.      *
  313.      * @see TokenInterface::getUser()
  314.      */
  315.     protected function getUser(): ?UserInterface
  316.     {
  317.         if (!$this->container->has('security.token_storage')) {
  318.             throw new \LogicException('The SecurityBundle is not registered in your application. Try running "composer require symfony/security-bundle".');
  319.         }
  320.         if (null === $token $this->container->get('security.token_storage')->getToken()) {
  321.             return null;
  322.         }
  323.         return $token->getUser();
  324.     }
  325.     /**
  326.      * Checks the validity of a CSRF token.
  327.      *
  328.      * @param string      $id    The id used when generating the token
  329.      * @param string|null $token The actual token sent with the request that should be validated
  330.      */
  331.     protected function isCsrfTokenValid(string $id, #[\SensitiveParameter] ?string $token): bool
  332.     {
  333.         if (!$this->container->has('security.csrf.token_manager')) {
  334.             throw new \LogicException('CSRF protection is not enabled in your application. Enable it with the "csrf_protection" key in "config/packages/framework.yaml".');
  335.         }
  336.         return $this->container->get('security.csrf.token_manager')->isTokenValid(new CsrfToken($id$token));
  337.     }
  338.     /**
  339.      * Adds a Link HTTP header to the current response.
  340.      *
  341.      * @see https://tools.ietf.org/html/rfc5988
  342.      */
  343.     protected function addLink(Request $requestLinkInterface $link): void
  344.     {
  345.         if (!class_exists(AddLinkHeaderListener::class)) {
  346.             throw new \LogicException('You cannot use the "addLink" method if the WebLink component is not available. Try running "composer require symfony/web-link".');
  347.         }
  348.         if (null === $linkProvider $request->attributes->get('_links')) {
  349.             $request->attributes->set('_links', new GenericLinkProvider([$link]));
  350.             return;
  351.         }
  352.         $request->attributes->set('_links'$linkProvider->withLink($link));
  353.     }
  354.     /**
  355.      * @param LinkInterface[] $links
  356.      */
  357.     protected function sendEarlyHints(iterable $links = [], ?Response $response null): Response
  358.     {
  359.         if (!$this->container->has('web_link.http_header_serializer')) {
  360.             throw new \LogicException('You cannot use the "sendEarlyHints" method if the WebLink component is not available. Try running "composer require symfony/web-link".');
  361.         }
  362.         $response ??= new Response();
  363.         $populatedLinks = [];
  364.         foreach ($links as $link) {
  365.             if ($link instanceof EvolvableLinkInterface && !$link->getRels()) {
  366.                 $link $link->withRel('preload');
  367.             }
  368.             $populatedLinks[] = $link;
  369.         }
  370.         $response->headers->set('Link'$this->container->get('web_link.http_header_serializer')->serialize($populatedLinks), false);
  371.         $response->sendHeaders(103);
  372.         return $response;
  373.     }
  374. }