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

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 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 <fabien@symfony.com>
  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.             @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);
  188.             return $this->container->get('templating')->render($view$parameters);
  189.         }
  190.         if (!$this->container->has('twig')) {
  191.             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".');
  192.         }
  193.         return $this->container->get('twig')->render($view$parameters);
  194.     }
  195.     /**
  196.      * Renders a view.
  197.      *
  198.      * @final
  199.      */
  200.     protected function render(string $view, array $parameters = [], Response $response null): Response
  201.     {
  202.         if ($this->container->has('templating')) {
  203.             @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);
  204.             $content $this->container->get('templating')->render($view$parameters);
  205.         } elseif ($this->container->has('twig')) {
  206.             $content $this->container->get('twig')->render($view$parameters);
  207.         } else {
  208.             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".');
  209.         }
  210.         if (null === $response) {
  211.             $response = new Response();
  212.         }
  213.         $response->setContent($content);
  214.         return $response;
  215.     }
  216.     /**
  217.      * Streams a view.
  218.      *
  219.      * @final
  220.      */
  221.     protected function stream(string $view, array $parameters = [], StreamedResponse $response null): StreamedResponse
  222.     {
  223.         if ($this->container->has('templating')) {
  224.             @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);
  225.             $templating $this->container->get('templating');
  226.             $callback = function () use ($templating$view$parameters) {
  227.                 $templating->stream($view$parameters);
  228.             };
  229.         } elseif ($this->container->has('twig')) {
  230.             $twig $this->container->get('twig');
  231.             $callback = function () use ($twig$view$parameters) {
  232.                 $twig->display($view$parameters);
  233.             };
  234.         } else {
  235.             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".');
  236.         }
  237.         if (null === $response) {
  238.             return new StreamedResponse($callback);
  239.         }
  240.         $response->setCallback($callback);
  241.         return $response;
  242.     }
  243.     /**
  244.      * Returns a NotFoundHttpException.
  245.      *
  246.      * This will result in a 404 response code. Usage example:
  247.      *
  248.      *     throw $this->createNotFoundException('Page not found!');
  249.      *
  250.      * @final
  251.      */
  252.     protected function createNotFoundException(string $message 'Not Found', \Exception $previous null): NotFoundHttpException
  253.     {
  254.         return new NotFoundHttpException($message$previous);
  255.     }
  256.     /**
  257.      * Returns an AccessDeniedException.
  258.      *
  259.      * This will result in a 403 response code. Usage example:
  260.      *
  261.      *     throw $this->createAccessDeniedException('Unable to access this page!');
  262.      *
  263.      * @throws \LogicException If the Security component is not available
  264.      *
  265.      * @final
  266.      */
  267.     protected function createAccessDeniedException(string $message 'Access Denied.', \Exception $previous null): AccessDeniedException
  268.     {
  269.         if (!class_exists(AccessDeniedException::class)) {
  270.             throw new \LogicException('You can not use the "createAccessDeniedException" method if the Security component is not available. Try running "composer require symfony/security-bundle".');
  271.         }
  272.         return new AccessDeniedException($message$previous);
  273.     }
  274.     /**
  275.      * Creates and returns a Form instance from the type of the form.
  276.      *
  277.      * @final
  278.      */
  279.     protected function createForm(string $type$data null, array $options = []): FormInterface
  280.     {
  281.         return $this->container->get('form.factory')->create($type$data$options);
  282.     }
  283.     /**
  284.      * Creates and returns a form builder instance.
  285.      *
  286.      * @final
  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.      * @final
  298.      */
  299.     protected function getDoctrine(): ManagerRegistry
  300.     {
  301.         if (!$this->container->has('doctrine')) {
  302.             throw new \LogicException('The DoctrineBundle is not registered in your application. Try running "composer require symfony/orm-pack".');
  303.         }
  304.         return $this->container->get('doctrine');
  305.     }
  306.     /**
  307.      * Get a user from the Security Token Storage.
  308.      *
  309.      * @return object|null
  310.      *
  311.      * @throws \LogicException If SecurityBundle is not available
  312.      *
  313.      * @see TokenInterface::getUser()
  314.      *
  315.      * @final
  316.      */
  317.     protected function getUser()
  318.     {
  319.         if (!$this->container->has('security.token_storage')) {
  320.             throw new \LogicException('The SecurityBundle is not registered in your application. Try running "composer require symfony/security-bundle".');
  321.         }
  322.         if (null === $token $this->container->get('security.token_storage')->getToken()) {
  323.             return null;
  324.         }
  325.         if (!\is_object($user $token->getUser())) {
  326.             // e.g. anonymous authentication
  327.             return null;
  328.         }
  329.         return $user;
  330.     }
  331.     /**
  332.      * Checks the validity of a CSRF token.
  333.      *
  334.      * @param string      $id    The id used when generating the token
  335.      * @param string|null $token The actual token sent with the request that should be validated
  336.      *
  337.      * @final
  338.      */
  339.     protected function isCsrfTokenValid(string $id, ?string $token): bool
  340.     {
  341.         if (!$this->container->has('security.csrf.token_manager')) {
  342.             throw new \LogicException('CSRF protection is not enabled in your application. Enable it with the "csrf_protection" key in "config/packages/framework.yaml".');
  343.         }
  344.         return $this->container->get('security.csrf.token_manager')->isTokenValid(new CsrfToken($id$token));
  345.     }
  346.     /**
  347.      * Dispatches a message to the bus.
  348.      *
  349.      * @param object|Envelope $message The message or the message pre-wrapped in an envelope
  350.      *
  351.      * @final
  352.      */
  353.     protected function dispatchMessage($message): Envelope
  354.     {
  355.         if (!$this->container->has('messenger.default_bus')) {
  356.             $message class_exists(Envelope::class) ? 'You need to define the "messenger.default_bus" configuration option.' 'Try running "composer require symfony/messenger".';
  357.             throw new \LogicException('The message bus is not enabled in your application. '.$message);
  358.         }
  359.         return $this->container->get('messenger.default_bus')->dispatch($message);
  360.     }
  361.     /**
  362.      * Adds a Link HTTP header to the current response.
  363.      *
  364.      * @see https://tools.ietf.org/html/rfc5988
  365.      *
  366.      * @final
  367.      */
  368.     protected function addLink(Request $requestLink $link)
  369.     {
  370.         if (!class_exists(AddLinkHeaderListener::class)) {
  371.             throw new \LogicException('You can not use the "addLink" method if the WebLink component is not available. Try running "composer require symfony/web-link".');
  372.         }
  373.         if (null === $linkProvider $request->attributes->get('_links')) {
  374.             $request->attributes->set('_links', new GenericLinkProvider([$link]));
  375.             return;
  376.         }
  377.         $request->attributes->set('_links'$linkProvider->withLink($link));
  378.     }
  379. }