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

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