vendor/symfony/symfony/src/Symfony/Bundle/FrameworkBundle/Controller/ControllerTrait.php line 397

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