vendor/symfony/framework-bundle/Controller/ControllerTrait.php line 294

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