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

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