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

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