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

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.     protected function getParameter(string $name): array|bool|string|int|float|\UnitEnum|null
  68.     {
  69.         if (!$this->container->has('parameter_bag')) {
  70.             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));
  71.         }
  72.         return $this->container->get('parameter_bag')->get($name);
  73.     }
  74.     public static function getSubscribedServices(): array
  75.     {
  76.         return [
  77.             'router' => '?'.RouterInterface::class,
  78.             'request_stack' => '?'.RequestStack::class,
  79.             'http_kernel' => '?'.HttpKernelInterface::class,
  80.             'serializer' => '?'.SerializerInterface::class,
  81.             'security.authorization_checker' => '?'.AuthorizationCheckerInterface::class,
  82.             'twig' => '?'.Environment::class,
  83.             'form.factory' => '?'.FormFactoryInterface::class,
  84.             'security.token_storage' => '?'.TokenStorageInterface::class,
  85.             'security.csrf.token_manager' => '?'.CsrfTokenManagerInterface::class,
  86.             'parameter_bag' => '?'.ContainerBagInterface::class,
  87.         ];
  88.     }
  89.     /**
  90.      * Generates a URL from the given parameters.
  91.      *
  92.      * @see UrlGeneratorInterface
  93.      */
  94.     protected function generateUrl(string $route, array $parameters = [], int $referenceType UrlGeneratorInterface::ABSOLUTE_PATH): string
  95.     {
  96.         return $this->container->get('router')->generate($route$parameters$referenceType);
  97.     }
  98.     /**
  99.      * Forwards the request to another controller.
  100.      *
  101.      * @param string $controller The controller name (a string like Bundle\BlogBundle\Controller\PostController::indexAction)
  102.      */
  103.     protected function forward(string $controller, array $path = [], array $query = []): Response
  104.     {
  105.         $request $this->container->get('request_stack')->getCurrentRequest();
  106.         $path['_controller'] = $controller;
  107.         $subRequest $request->duplicate($querynull$path);
  108.         return $this->container->get('http_kernel')->handle($subRequestHttpKernelInterface::SUB_REQUEST);
  109.     }
  110.     /**
  111.      * Returns a RedirectResponse to the given URL.
  112.      */
  113.     protected function redirect(string $urlint $status 302): RedirectResponse
  114.     {
  115.         return new RedirectResponse($url$status);
  116.     }
  117.     /**
  118.      * Returns a RedirectResponse to the given route with the given parameters.
  119.      */
  120.     protected function redirectToRoute(string $route, array $parameters = [], int $status 302): RedirectResponse
  121.     {
  122.         return $this->redirect($this->generateUrl($route$parameters), $status);
  123.     }
  124.     /**
  125.      * Returns a JsonResponse that uses the serializer component if enabled, or json_encode.
  126.      */
  127.     protected function json(mixed $dataint $status 200, array $headers = [], array $context = []): JsonResponse
  128.     {
  129.         if ($this->container->has('serializer')) {
  130.             $json $this->container->get('serializer')->serialize($data'json'array_merge([
  131.                 'json_encode_options' => JsonResponse::DEFAULT_ENCODING_OPTIONS,
  132.             ], $context));
  133.             return new JsonResponse($json$status$headerstrue);
  134.         }
  135.         return new JsonResponse($data$status$headers);
  136.     }
  137.     /**
  138.      * Returns a BinaryFileResponse object with original or customized file name and disposition header.
  139.      */
  140.     protected function file(\SplFileInfo|string $filestring $fileName nullstring $disposition ResponseHeaderBag::DISPOSITION_ATTACHMENT): BinaryFileResponse
  141.     {
  142.         $response = new BinaryFileResponse($file);
  143.         $response->setContentDisposition($dispositionnull === $fileName $response->getFile()->getFilename() : $fileName);
  144.         return $response;
  145.     }
  146.     /**
  147.      * Adds a flash message to the current session for type.
  148.      *
  149.      * @throws \LogicException
  150.      */
  151.     protected function addFlash(string $typemixed $message): void
  152.     {
  153.         try {
  154.             $this->container->get('request_stack')->getSession()->getFlashBag()->add($type$message);
  155.         } catch (SessionNotFoundException $e) {
  156.             throw new \LogicException('You cannot use the addFlash method if sessions are disabled. Enable them in "config/packages/framework.yaml".'0$e);
  157.         }
  158.     }
  159.     /**
  160.      * Checks if the attribute is granted against the current authentication token and optionally supplied subject.
  161.      *
  162.      * @throws \LogicException
  163.      */
  164.     protected function isGranted(mixed $attributemixed $subject null): bool
  165.     {
  166.         if (!$this->container->has('security.authorization_checker')) {
  167.             throw new \LogicException('The SecurityBundle is not registered in your application. Try running "composer require symfony/security-bundle".');
  168.         }
  169.         return $this->container->get('security.authorization_checker')->isGranted($attribute$subject);
  170.     }
  171.     /**
  172.      * Throws an exception unless the attribute is granted against the current authentication token and optionally
  173.      * supplied subject.
  174.      *
  175.      * @throws AccessDeniedException
  176.      */
  177.     protected function denyAccessUnlessGranted(mixed $attributemixed $subject nullstring $message 'Access Denied.'): void
  178.     {
  179.         if (!$this->isGranted($attribute$subject)) {
  180.             $exception $this->createAccessDeniedException($message);
  181.             $exception->setAttributes($attribute);
  182.             $exception->setSubject($subject);
  183.             throw $exception;
  184.         }
  185.     }
  186.     /**
  187.      * Returns a rendered view.
  188.      */
  189.     protected function renderView(string $view, array $parameters = []): string
  190.     {
  191.         if (!$this->container->has('twig')) {
  192.             throw new \LogicException('You cannot use the "renderView" method if the Twig Bundle is not available. Try running "composer require symfony/twig-bundle".');
  193.         }
  194.         return $this->container->get('twig')->render($view$parameters);
  195.     }
  196.     /**
  197.      * Renders a view.
  198.      */
  199.     protected function render(string $view, array $parameters = [], Response $response null): Response
  200.     {
  201.         $content $this->renderView($view$parameters);
  202.         if (null === $response) {
  203.             $response = new Response();
  204.         }
  205.         $response->setContent($content);
  206.         return $response;
  207.     }
  208.     /**
  209.      * Renders a view and sets the appropriate status code when a form is listed in parameters.
  210.      *
  211.      * If an invalid form is found in the list of parameters, a 422 status code is returned.
  212.      */
  213.     protected function renderForm(string $view, array $parameters = [], Response $response null): Response
  214.     {
  215.         if (null === $response) {
  216.             $response = new Response();
  217.         }
  218.         foreach ($parameters as $k => $v) {
  219.             if ($v instanceof FormView) {
  220.                 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));
  221.             }
  222.             if (!$v instanceof FormInterface) {
  223.                 continue;
  224.             }
  225.             $parameters[$k] = $v->createView();
  226.             if (200 === $response->getStatusCode() && $v->isSubmitted() && !$v->isValid()) {
  227.                 $response->setStatusCode(422);
  228.             }
  229.         }
  230.         return $this->render($view$parameters$response);
  231.     }
  232.     /**
  233.      * Streams a view.
  234.      */
  235.     protected function stream(string $view, array $parameters = [], StreamedResponse $response null): StreamedResponse
  236.     {
  237.         if (!$this->container->has('twig')) {
  238.             throw new \LogicException('You cannot use the "stream" method if the Twig Bundle is not available. Try running "composer require symfony/twig-bundle".');
  239.         }
  240.         $twig $this->container->get('twig');
  241.         $callback = function () use ($twig$view$parameters) {
  242.             $twig->display($view$parameters);
  243.         };
  244.         if (null === $response) {
  245.             return new StreamedResponse($callback);
  246.         }
  247.         $response->setCallback($callback);
  248.         return $response;
  249.     }
  250.     /**
  251.      * Returns a NotFoundHttpException.
  252.      *
  253.      * This will result in a 404 response code. Usage example:
  254.      *
  255.      *     throw $this->createNotFoundException('Page not found!');
  256.      */
  257.     protected function createNotFoundException(string $message 'Not Found'\Throwable $previous null): NotFoundHttpException
  258.     {
  259.         return new NotFoundHttpException($message$previous);
  260.     }
  261.     /**
  262.      * Returns an AccessDeniedException.
  263.      *
  264.      * This will result in a 403 response code. Usage example:
  265.      *
  266.      *     throw $this->createAccessDeniedException('Unable to access this page!');
  267.      *
  268.      * @throws \LogicException If the Security component is not available
  269.      */
  270.     protected function createAccessDeniedException(string $message 'Access Denied.'\Throwable $previous null): AccessDeniedException
  271.     {
  272.         if (!class_exists(AccessDeniedException::class)) {
  273.             throw new \LogicException('You cannot use the "createAccessDeniedException" method if the Security component is not available. Try running "composer require symfony/security-bundle".');
  274.         }
  275.         return new AccessDeniedException($message$previous);
  276.     }
  277.     /**
  278.      * Creates and returns a Form instance from the type of the form.
  279.      */
  280.     protected function createForm(string $typemixed $data null, array $options = []): FormInterface
  281.     {
  282.         return $this->container->get('form.factory')->create($type$data$options);
  283.     }
  284.     /**
  285.      * Creates and returns a form builder instance.
  286.      */
  287.     protected function createFormBuilder(mixed $data null, array $options = []): FormBuilderInterface
  288.     {
  289.         return $this->container->get('form.factory')->createBuilder(FormType::class, $data$options);
  290.     }
  291.     /**
  292.      * Get a user from the Security Token Storage.
  293.      *
  294.      * @throws \LogicException If SecurityBundle is not available
  295.      *
  296.      * @see TokenInterface::getUser()
  297.      */
  298.     protected function getUser(): ?UserInterface
  299.     {
  300.         if (!$this->container->has('security.token_storage')) {
  301.             throw new \LogicException('The SecurityBundle is not registered in your application. Try running "composer require symfony/security-bundle".');
  302.         }
  303.         if (null === $token $this->container->get('security.token_storage')->getToken()) {
  304.             return null;
  305.         }
  306.         return $token->getUser();
  307.     }
  308.     /**
  309.      * Checks the validity of a CSRF token.
  310.      *
  311.      * @param string      $id    The id used when generating the token
  312.      * @param string|null $token The actual token sent with the request that should be validated
  313.      */
  314.     protected function isCsrfTokenValid(string $id, ?string $token): bool
  315.     {
  316.         if (!$this->container->has('security.csrf.token_manager')) {
  317.             throw new \LogicException('CSRF protection is not enabled in your application. Enable it with the "csrf_protection" key in "config/packages/framework.yaml".');
  318.         }
  319.         return $this->container->get('security.csrf.token_manager')->isTokenValid(new CsrfToken($id$token));
  320.     }
  321.     /**
  322.      * Adds a Link HTTP header to the current response.
  323.      *
  324.      * @see https://tools.ietf.org/html/rfc5988
  325.      */
  326.     protected function addLink(Request $requestLinkInterface $link): void
  327.     {
  328.         if (!class_exists(AddLinkHeaderListener::class)) {
  329.             throw new \LogicException('You cannot use the "addLink" method if the WebLink component is not available. Try running "composer require symfony/web-link".');
  330.         }
  331.         if (null === $linkProvider $request->attributes->get('_links')) {
  332.             $request->attributes->set('_links', new GenericLinkProvider([$link]));
  333.             return;
  334.         }
  335.         $request->attributes->set('_links'$linkProvider->withLink($link));
  336.     }
  337. }