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

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