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

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