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

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