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

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 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\Form\FormView;
  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\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\ServiceSubscriberInterface;
  43. use Twig\Environment;
  44. /**
  45.  * Provides shortcuts for HTTP-related features in controllers.
  46.  *
  47.  * @author Fabien Potencier <fabien@symfony.com>
  48.  */
  49. abstract class AbstractController implements ServiceSubscriberInterface
  50. {
  51.     /**
  52.      * @var ContainerInterface
  53.      */
  54.     protected $container;
  55.     /**
  56.      * @required
  57.      */
  58.     public function setContainer(ContainerInterface $container): ?ContainerInterface
  59.     {
  60.         $previous $this->container;
  61.         $this->container $container;
  62.         return $previous;
  63.     }
  64.     /**
  65.      * Gets a container parameter by its name.
  66.      *
  67.      * @return array|bool|float|int|string|null
  68.      */
  69.     protected function getParameter(string $name): array|bool|float|int|string|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.     protected function redirect(string $urlint $status 302): RedirectResponse
  116.     {
  117.         return new RedirectResponse($url$status);
  118.     }
  119.     /**
  120.      * Returns a RedirectResponse to the given route with the given parameters.
  121.      */
  122.     protected function redirectToRoute(string $route, array $parameters = [], int $status 302): RedirectResponse
  123.     {
  124.         return $this->redirect($this->generateUrl($route$parameters), $status);
  125.     }
  126.     /**
  127.      * Returns a JsonResponse that uses the serializer component if enabled, or json_encode.
  128.      */
  129.     protected function json(mixed $dataint $status 200, array $headers = [], array $context = []): JsonResponse
  130.     {
  131.         if ($this->container->has('serializer')) {
  132.             $json $this->container->get('serializer')->serialize($data'json'array_merge([
  133.                 'json_encode_options' => JsonResponse::DEFAULT_ENCODING_OPTIONS,
  134.             ], $context));
  135.             return new JsonResponse($json$status$headerstrue);
  136.         }
  137.         return new JsonResponse($data$status$headers);
  138.     }
  139.     /**
  140.      * Returns a BinaryFileResponse object with original or customized file name and disposition header.
  141.      */
  142.     protected function file(\SplFileInfo|string $filestring $fileName nullstring $disposition ResponseHeaderBag::DISPOSITION_ATTACHMENT): BinaryFileResponse
  143.     {
  144.         $response = new BinaryFileResponse($file);
  145.         $response->setContentDisposition($dispositionnull === $fileName $response->getFile()->getFilename() : $fileName);
  146.         return $response;
  147.     }
  148.     /**
  149.      * Adds a flash message to the current session for type.
  150.      *
  151.      * @throws \LogicException
  152.      */
  153.     protected function addFlash(string $typemixed $message): void
  154.     {
  155.         try {
  156.             $this->container->get('request_stack')->getSession()->getFlashBag()->add($type$message);
  157.         } catch (SessionNotFoundException $e) {
  158.             throw new \LogicException('You cannot use the addFlash method if sessions are disabled. Enable them in "config/packages/framework.yaml".'0$e);
  159.         }
  160.     }
  161.     /**
  162.      * Checks if the attribute is granted against the current authentication token and optionally supplied subject.
  163.      *
  164.      * @throws \LogicException
  165.      */
  166.     protected function isGranted(mixed $attributemixed $subject null): bool
  167.     {
  168.         if (!$this->container->has('security.authorization_checker')) {
  169.             throw new \LogicException('The SecurityBundle is not registered in your application. Try running "composer require symfony/security-bundle".');
  170.         }
  171.         return $this->container->get('security.authorization_checker')->isGranted($attribute$subject);
  172.     }
  173.     /**
  174.      * Throws an exception unless the attribute is granted against the current authentication token and optionally
  175.      * supplied subject.
  176.      *
  177.      * @throws AccessDeniedException
  178.      */
  179.     protected function denyAccessUnlessGranted(mixed $attributemixed $subject nullstring $message 'Access Denied.'): void
  180.     {
  181.         if (!$this->isGranted($attribute$subject)) {
  182.             $exception $this->createAccessDeniedException($message);
  183.             $exception->setAttributes($attribute);
  184.             $exception->setSubject($subject);
  185.             throw $exception;
  186.         }
  187.     }
  188.     /**
  189.      * Returns a rendered view.
  190.      */
  191.     protected function renderView(string $view, array $parameters = []): string
  192.     {
  193.         if (!$this->container->has('twig')) {
  194.             throw new \LogicException('You cannot use the "renderView" method if the Twig Bundle is not available. Try running "composer require symfony/twig-bundle".');
  195.         }
  196.         return $this->container->get('twig')->render($view$parameters);
  197.     }
  198.     /**
  199.      * Renders a view.
  200.      */
  201.     protected function render(string $view, array $parameters = [], Response $response null): Response
  202.     {
  203.         $content $this->renderView($view$parameters);
  204.         if (null === $response) {
  205.             $response = new Response();
  206.         }
  207.         $response->setContent($content);
  208.         return $response;
  209.     }
  210.     /**
  211.      * Renders a view and sets the appropriate status code when a form is listed in parameters.
  212.      *
  213.      * If an invalid form is found in the list of parameters, a 422 status code is returned.
  214.      */
  215.     protected function renderForm(string $view, array $parameters = [], Response $response null): Response
  216.     {
  217.         if (null === $response) {
  218.             $response = new Response();
  219.         }
  220.         foreach ($parameters as $k => $v) {
  221.             if ($v instanceof FormView) {
  222.                 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));
  223.             }
  224.             if (!$v instanceof FormInterface) {
  225.                 continue;
  226.             }
  227.             $parameters[$k] = $v->createView();
  228.             if (200 === $response->getStatusCode() && $v->isSubmitted() && !$v->isValid()) {
  229.                 $response->setStatusCode(422);
  230.             }
  231.         }
  232.         return $this->render($view$parameters$response);
  233.     }
  234.     /**
  235.      * Streams a view.
  236.      */
  237.     protected function stream(string $view, array $parameters = [], StreamedResponse $response null): StreamedResponse
  238.     {
  239.         if (!$this->container->has('twig')) {
  240.             throw new \LogicException('You cannot use the "stream" method if the Twig Bundle is not available. Try running "composer require symfony/twig-bundle".');
  241.         }
  242.         $twig $this->container->get('twig');
  243.         $callback = function () use ($twig$view$parameters) {
  244.             $twig->display($view$parameters);
  245.         };
  246.         if (null === $response) {
  247.             return new StreamedResponse($callback);
  248.         }
  249.         $response->setCallback($callback);
  250.         return $response;
  251.     }
  252.     /**
  253.      * Returns a NotFoundHttpException.
  254.      *
  255.      * This will result in a 404 response code. Usage example:
  256.      *
  257.      *     throw $this->createNotFoundException('Page not found!');
  258.      */
  259.     protected function createNotFoundException(string $message 'Not Found'\Throwable $previous null): NotFoundHttpException
  260.     {
  261.         return new NotFoundHttpException($message$previous);
  262.     }
  263.     /**
  264.      * Returns an AccessDeniedException.
  265.      *
  266.      * This will result in a 403 response code. Usage example:
  267.      *
  268.      *     throw $this->createAccessDeniedException('Unable to access this page!');
  269.      *
  270.      * @throws \LogicException If the Security component is not available
  271.      */
  272.     protected function createAccessDeniedException(string $message 'Access Denied.'\Throwable $previous null): AccessDeniedException
  273.     {
  274.         if (!class_exists(AccessDeniedException::class)) {
  275.             throw new \LogicException('You cannot use the "createAccessDeniedException" method if the Security component is not available. Try running "composer require symfony/security-bundle".');
  276.         }
  277.         return new AccessDeniedException($message$previous);
  278.     }
  279.     /**
  280.      * Creates and returns a Form instance from the type of the form.
  281.      */
  282.     protected function createForm(string $typemixed $data null, array $options = []): FormInterface
  283.     {
  284.         return $this->container->get('form.factory')->create($type$data$options);
  285.     }
  286.     /**
  287.      * Creates and returns a form builder instance.
  288.      */
  289.     protected function createFormBuilder(mixed $data null, array $options = []): FormBuilderInterface
  290.     {
  291.         return $this->container->get('form.factory')->createBuilder(FormType::class, $data$options);
  292.     }
  293.     /**
  294.      * Get a user from the Security Token Storage.
  295.      *
  296.      * @throws \LogicException If SecurityBundle is not available
  297.      *
  298.      * @see TokenInterface::getUser()
  299.      */
  300.     protected function getUser(): ?UserInterface
  301.     {
  302.         if (!$this->container->has('security.token_storage')) {
  303.             throw new \LogicException('The SecurityBundle is not registered in your application. Try running "composer require symfony/security-bundle".');
  304.         }
  305.         if (null === $token $this->container->get('security.token_storage')->getToken()) {
  306.             return null;
  307.         }
  308.         return $token->getUser();
  309.     }
  310.     /**
  311.      * Checks the validity of a CSRF token.
  312.      *
  313.      * @param string      $id    The id used when generating the token
  314.      * @param string|null $token The actual token sent with the request that should be validated
  315.      */
  316.     protected function isCsrfTokenValid(string $id, ?string $token): bool
  317.     {
  318.         if (!$this->container->has('security.csrf.token_manager')) {
  319.             throw new \LogicException('CSRF protection is not enabled in your application. Enable it with the "csrf_protection" key in "config/packages/framework.yaml".');
  320.         }
  321.         return $this->container->get('security.csrf.token_manager')->isTokenValid(new CsrfToken($id$token));
  322.     }
  323.     /**
  324.      * Adds a Link HTTP header to the current response.
  325.      *
  326.      * @see https://tools.ietf.org/html/rfc5988
  327.      */
  328.     protected function addLink(Request $requestLinkInterface $link): void
  329.     {
  330.         if (!class_exists(AddLinkHeaderListener::class)) {
  331.             throw new \LogicException('You cannot use the "addLink" method if the WebLink component is not available. Try running "composer require symfony/web-link".');
  332.         }
  333.         if (null === $linkProvider $request->attributes->get('_links')) {
  334.             $request->attributes->set('_links', new GenericLinkProvider([$link]));
  335.             return;
  336.         }
  337.         $request->attributes->set('_links'$linkProvider->withLink($link));
  338.     }
  339. }