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

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