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

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\HttpFoundation\BinaryFileResponse;
  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\SessionInterface;
  28. use Symfony\Component\HttpFoundation\StreamedResponse;
  29. use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
  30. use Symfony\Component\HttpKernel\HttpKernelInterface;
  31. use Symfony\Component\Messenger\Envelope;
  32. use Symfony\Component\Messenger\MessageBusInterface;
  33. use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
  34. use Symfony\Component\Routing\RouterInterface;
  35. use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
  36. use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
  37. use Symfony\Component\Security\Core\Exception\AccessDeniedException;
  38. use Symfony\Component\Security\Core\User\UserInterface;
  39. use Symfony\Component\Security\Csrf\CsrfToken;
  40. use Symfony\Component\Security\Csrf\CsrfTokenManagerInterface;
  41. use Symfony\Component\Serializer\SerializerInterface;
  42. use Symfony\Component\WebLink\EventListener\AddLinkHeaderListener;
  43. use Symfony\Component\WebLink\GenericLinkProvider;
  44. use Symfony\Contracts\Service\ServiceSubscriberInterface;
  45. use Twig\Environment;
  46. /**
  47.  * Provides common features needed in controllers.
  48.  *
  49.  * @author Fabien Potencier <fabien@symfony.com>
  50.  */
  51. abstract class AbstractController implements ServiceSubscriberInterface
  52. {
  53.     /**
  54.      * @var ContainerInterface
  55.      */
  56.     protected $container;
  57.     /**
  58.      * @internal
  59.      * @required
  60.      */
  61.     public function setContainer(ContainerInterface $container): ?ContainerInterface
  62.     {
  63.         $previous $this->container;
  64.         $this->container $container;
  65.         return $previous;
  66.     }
  67.     /**
  68.      * Gets a container parameter by its name.
  69.      *
  70.      * @return mixed
  71.      */
  72.     protected function getParameter(string $name)
  73.     {
  74.         if (!$this->container->has('parameter_bag')) {
  75.             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));
  76.         }
  77.         return $this->container->get('parameter_bag')->get($name);
  78.     }
  79.     public static function getSubscribedServices()
  80.     {
  81.         return [
  82.             'router' => '?'.RouterInterface::class,
  83.             'request_stack' => '?'.RequestStack::class,
  84.             'http_kernel' => '?'.HttpKernelInterface::class,
  85.             'serializer' => '?'.SerializerInterface::class,
  86.             'session' => '?'.SessionInterface::class,
  87.             'security.authorization_checker' => '?'.AuthorizationCheckerInterface::class,
  88.             'twig' => '?'.Environment::class,
  89.             'doctrine' => '?'.ManagerRegistry::class,
  90.             'form.factory' => '?'.FormFactoryInterface::class,
  91.             'security.token_storage' => '?'.TokenStorageInterface::class,
  92.             'security.csrf.token_manager' => '?'.CsrfTokenManagerInterface::class,
  93.             'parameter_bag' => '?'.ContainerBagInterface::class,
  94.             'message_bus' => '?'.MessageBusInterface::class,
  95.             'messenger.default_bus' => '?'.MessageBusInterface::class,
  96.         ];
  97.     }
  98.     /**
  99.      * Returns true if the service id is defined.
  100.      */
  101.     protected function has(string $id): bool
  102.     {
  103.         return $this->container->has($id);
  104.     }
  105.     /**
  106.      * Gets a container service by its id.
  107.      *
  108.      * @return object The service
  109.      */
  110.     protected function get(string $id): object
  111.     {
  112.         return $this->container->get($id);
  113.     }
  114.     /**
  115.      * Generates a URL from the given parameters.
  116.      *
  117.      * @see UrlGeneratorInterface
  118.      */
  119.     protected function generateUrl(string $route, array $parameters = [], int $referenceType UrlGeneratorInterface::ABSOLUTE_PATH): string
  120.     {
  121.         return $this->container->get('router')->generate($route$parameters$referenceType);
  122.     }
  123.     /**
  124.      * Forwards the request to another controller.
  125.      *
  126.      * @param string $controller The controller name (a string like Bundle\BlogBundle\Controller\PostController::indexAction)
  127.      */
  128.     protected function forward(string $controller, array $path = [], array $query = []): Response
  129.     {
  130.         $request $this->container->get('request_stack')->getCurrentRequest();
  131.         $path['_controller'] = $controller;
  132.         $subRequest $request->duplicate($querynull$path);
  133.         return $this->container->get('http_kernel')->handle($subRequestHttpKernelInterface::SUB_REQUEST);
  134.     }
  135.     /**
  136.      * Returns a RedirectResponse to the given URL.
  137.      */
  138.     protected function redirect(string $urlint $status 302): RedirectResponse
  139.     {
  140.         return new RedirectResponse($url$status);
  141.     }
  142.     /**
  143.      * Returns a RedirectResponse to the given route with the given parameters.
  144.      */
  145.     protected function redirectToRoute(string $route, array $parameters = [], int $status 302): RedirectResponse
  146.     {
  147.         return $this->redirect($this->generateUrl($route$parameters), $status);
  148.     }
  149.     /**
  150.      * Returns a JsonResponse that uses the serializer component if enabled, or json_encode.
  151.      */
  152.     protected function json($dataint $status 200, array $headers = [], array $context = []): JsonResponse
  153.     {
  154.         if ($this->container->has('serializer')) {
  155.             $json $this->container->get('serializer')->serialize($data'json'array_merge([
  156.                 'json_encode_options' => JsonResponse::DEFAULT_ENCODING_OPTIONS,
  157.             ], $context));
  158.             return new JsonResponse($json$status$headerstrue);
  159.         }
  160.         return new JsonResponse($data$status$headers);
  161.     }
  162.     /**
  163.      * Returns a BinaryFileResponse object with original or customized file name and disposition header.
  164.      *
  165.      * @param \SplFileInfo|string $file File object or path to file to be sent as response
  166.      */
  167.     protected function file($filestring $fileName nullstring $disposition ResponseHeaderBag::DISPOSITION_ATTACHMENT): BinaryFileResponse
  168.     {
  169.         $response = new BinaryFileResponse($file);
  170.         $response->setContentDisposition($dispositionnull === $fileName $response->getFile()->getFilename() : $fileName);
  171.         return $response;
  172.     }
  173.     /**
  174.      * Adds a flash message to the current session for type.
  175.      *
  176.      * @throws \LogicException
  177.      */
  178.     protected function addFlash(string $type$message): void
  179.     {
  180.         if (!$this->container->has('session')) {
  181.             throw new \LogicException('You can not use the addFlash method if sessions are disabled. Enable them in "config/packages/framework.yaml".');
  182.         }
  183.         $this->container->get('session')->getFlashBag()->add($type$message);
  184.     }
  185.     /**
  186.      * Checks if the attribute is granted against the current authentication token and optionally supplied subject.
  187.      *
  188.      * @throws \LogicException
  189.      */
  190.     protected function isGranted($attribute$subject null): bool
  191.     {
  192.         if (!$this->container->has('security.authorization_checker')) {
  193.             throw new \LogicException('The SecurityBundle is not registered in your application. Try running "composer require symfony/security-bundle".');
  194.         }
  195.         return $this->container->get('security.authorization_checker')->isGranted($attribute$subject);
  196.     }
  197.     /**
  198.      * Throws an exception unless the attribute is granted against the current authentication token and optionally
  199.      * supplied subject.
  200.      *
  201.      * @throws AccessDeniedException
  202.      */
  203.     protected function denyAccessUnlessGranted($attribute$subject nullstring $message 'Access Denied.'): void
  204.     {
  205.         if (!$this->isGranted($attribute$subject)) {
  206.             $exception $this->createAccessDeniedException($message);
  207.             $exception->setAttributes($attribute);
  208.             $exception->setSubject($subject);
  209.             throw $exception;
  210.         }
  211.     }
  212.     /**
  213.      * Returns a rendered view.
  214.      */
  215.     protected function renderView(string $view, array $parameters = []): string
  216.     {
  217.         if (!$this->container->has('twig')) {
  218.             throw new \LogicException('You can not use the "renderView" method if the Twig Bundle is not available. Try running "composer require symfony/twig-bundle".');
  219.         }
  220.         return $this->container->get('twig')->render($view$parameters);
  221.     }
  222.     /**
  223.      * Renders a view.
  224.      */
  225.     protected function render(string $view, array $parameters = [], Response $response null): Response
  226.     {
  227.         $content $this->renderView($view$parameters);
  228.         if (null === $response) {
  229.             $response = new Response();
  230.         }
  231.         $response->setContent($content);
  232.         return $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 can not 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 can not 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 $type$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($data null, array $options = []): FormBuilderInterface
  290.     {
  291.         return $this->container->get('form.factory')->createBuilder(FormType::class, $data$options);
  292.     }
  293.     /**
  294.      * Shortcut to return the Doctrine Registry service.
  295.      *
  296.      * @throws \LogicException If DoctrineBundle is not available
  297.      */
  298.     protected function getDoctrine(): ManagerRegistry
  299.     {
  300.         if (!$this->container->has('doctrine')) {
  301.             throw new \LogicException('The DoctrineBundle is not registered in your application. Try running "composer require symfony/orm-pack".');
  302.         }
  303.         return $this->container->get('doctrine');
  304.     }
  305.     /**
  306.      * Get a user from the Security Token Storage.
  307.      *
  308.      * @return UserInterface|object|null
  309.      *
  310.      * @throws \LogicException If SecurityBundle is not available
  311.      *
  312.      * @see TokenInterface::getUser()
  313.      */
  314.     protected function getUser()
  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.         if (!\is_object($user $token->getUser())) {
  323.             // e.g. anonymous authentication
  324.             return null;
  325.         }
  326.         return $user;
  327.     }
  328.     /**
  329.      * Checks the validity of a CSRF token.
  330.      *
  331.      * @param string      $id    The id used when generating the token
  332.      * @param string|null $token The actual token sent with the request that should be validated
  333.      */
  334.     protected function isCsrfTokenValid(string $id, ?string $token): bool
  335.     {
  336.         if (!$this->container->has('security.csrf.token_manager')) {
  337.             throw new \LogicException('CSRF protection is not enabled in your application. Enable it with the "csrf_protection" key in "config/packages/framework.yaml".');
  338.         }
  339.         return $this->container->get('security.csrf.token_manager')->isTokenValid(new CsrfToken($id$token));
  340.     }
  341.     /**
  342.      * Dispatches a message to the bus.
  343.      *
  344.      * @param object|Envelope $message The message or the message pre-wrapped in an envelope
  345.      */
  346.     protected function dispatchMessage($message, array $stamps = []): Envelope
  347.     {
  348.         if (!$this->container->has('messenger.default_bus')) {
  349.             $message class_exists(Envelope::class) ? 'You need to define the "messenger.default_bus" configuration option.' 'Try running "composer require symfony/messenger".';
  350.             throw new \LogicException('The message bus is not enabled in your application. '.$message);
  351.         }
  352.         return $this->container->get('messenger.default_bus')->dispatch($message$stamps);
  353.     }
  354.     /**
  355.      * Adds a Link HTTP header to the current response.
  356.      *
  357.      * @see https://tools.ietf.org/html/rfc5988
  358.      */
  359.     protected function addLink(Request $requestLinkInterface $link): void
  360.     {
  361.         if (!class_exists(AddLinkHeaderListener::class)) {
  362.             throw new \LogicException('You can not use the "addLink" method if the WebLink component is not available. Try running "composer require symfony/web-link".');
  363.         }
  364.         if (null === $linkProvider $request->attributes->get('_links')) {
  365.             $request->attributes->set('_links', new GenericLinkProvider([$link]));
  366.             return;
  367.         }
  368.         $request->attributes->set('_links'$linkProvider->withLink($link));
  369.     }
  370. }