vendor/symfony/framework-bundle/Controller/AbstractController.php line 401

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\Persistence\ManagerRegistry;
  12. use Psr\Container\ContainerInterface;
  13. use Psr\Link\LinkInterface;
  14. use Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException;
  15. use Symfony\Component\DependencyInjection\ParameterBag\ContainerBagInterface;
  16. use Symfony\Component\Form\Extension\Core\Type\FormType;
  17. use Symfony\Component\Form\FormBuilderInterface;
  18. use Symfony\Component\Form\FormFactoryInterface;
  19. use Symfony\Component\Form\FormInterface;
  20. use Symfony\Component\Form\FormView;
  21. use Symfony\Component\HttpFoundation\BinaryFileResponse;
  22. use Symfony\Component\HttpFoundation\Exception\SessionNotFoundException;
  23. use Symfony\Component\HttpFoundation\JsonResponse;
  24. use Symfony\Component\HttpFoundation\RedirectResponse;
  25. use Symfony\Component\HttpFoundation\Request;
  26. use Symfony\Component\HttpFoundation\RequestStack;
  27. use Symfony\Component\HttpFoundation\Response;
  28. use Symfony\Component\HttpFoundation\ResponseHeaderBag;
  29. use Symfony\Component\HttpFoundation\Session\SessionInterface;
  30. use Symfony\Component\HttpFoundation\StreamedResponse;
  31. use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
  32. use Symfony\Component\HttpKernel\HttpKernelInterface;
  33. use Symfony\Component\Messenger\Envelope;
  34. use Symfony\Component\Messenger\MessageBusInterface;
  35. use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
  36. use Symfony\Component\Routing\RouterInterface;
  37. use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
  38. use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
  39. use Symfony\Component\Security\Core\Exception\AccessDeniedException;
  40. use Symfony\Component\Security\Core\User\UserInterface;
  41. use Symfony\Component\Security\Csrf\CsrfToken;
  42. use Symfony\Component\Security\Csrf\CsrfTokenManagerInterface;
  43. use Symfony\Component\Serializer\SerializerInterface;
  44. use Symfony\Component\WebLink\EventListener\AddLinkHeaderListener;
  45. use Symfony\Component\WebLink\GenericLinkProvider;
  46. use Symfony\Contracts\Service\ServiceSubscriberInterface;
  47. use Twig\Environment;
  48. use AppBundle\Plans\PlanDocuments;
  49. /**
  50.  * Provides shortcuts for HTTP-related features in controllers.
  51.  *
  52.  * @author Fabien Potencier <[email protected]>
  53.  */
  54. abstract class AbstractController implements ServiceSubscriberInterface
  55. {
  56.     /**
  57.      * @var ContainerInterface
  58.      */
  59.     protected $container;
  60.     protected $container2;
  61.     /**
  62.      * @required
  63.      */
  64.     public function setContainer(ContainerInterface $container): ?ContainerInterface
  65.     {
  66.         
  67.         $previous $this->container;
  68.         $this->container $container;
  69.         return $previous;
  70.     }
  71.     public function setContainer2(ContainerInterface $container): ?ContainerInterface
  72.     {
  73.         
  74.         $previous $this->container2;
  75.         $this->container2 $container;
  76.         return $this->container2;
  77.     }
  78.     /**
  79.      * Gets a container parameter by its name.
  80.      *
  81.      * @return array|bool|float|int|string|\UnitEnum|null
  82.      */
  83.     protected function getParameter(string $name)
  84.     {
  85.         if (!$this->container->has('parameter_bag')) {
  86.             throw new ServiceNotFoundException('parameter_bag.'nullnull, [], sprintf('The "%s::getParameter()" method is missing a parameter bag to work properly. Did you forget to register your controller as a service subscriber? This can be fixed either by using autoconfiguration or by manually wiring a "parameter_bag" in the service locator passed to the controller.', static::class));
  87.         }
  88.         return $this->container->get('parameter_bag')->get($name);
  89.     }
  90.     public static function getSubscribedServices()
  91.     {
  92.         
  93.         return [            
  94.             'router' => '?'.RouterInterface::class,
  95.             'request_stack' => '?'.RequestStack::class,
  96.             'http_kernel' => '?'.HttpKernelInterface::class,
  97.             'serializer' => '?'.SerializerInterface::class,
  98.             'session' => '?'.SessionInterface::class,
  99.             'security.authorization_checker' => '?'.AuthorizationCheckerInterface::class,
  100.             'twig' => '?'.Environment::class,
  101.             'doctrine' => '?'.ManagerRegistry::class, // to be removed in 6.0
  102.             'form.factory' => '?'.FormFactoryInterface::class,
  103.             'security.token_storage' => '?'.TokenStorageInterface::class,
  104.             'security.csrf.token_manager' => '?'.CsrfTokenManagerInterface::class,
  105.             'parameter_bag' => '?'.ContainerBagInterface::class,
  106.             'message_bus' => '?'.MessageBusInterface::class, // to be removed in 6.0
  107.             'messenger.default_bus' => '?'.MessageBusInterface::class, // to be removed in 6.0
  108.         ];
  109.     }
  110.     /**
  111.      * Returns true if the service id is defined.
  112.      *
  113.      * @deprecated since Symfony 5.4, use method or constructor injection in your controller instead
  114.      */
  115.     protected function has(string $id): bool
  116.     {
  117.         trigger_deprecation('symfony/framework-bundle''5.4''Method "%s()" is deprecated, use method or constructor injection in your controller instead.'__METHOD__);
  118.         return $this->container->has($id);
  119.     }
  120.     /**
  121.      * Gets a container service by its id.
  122.      *
  123.      * @return object The service
  124.      *
  125.      * @deprecated since Symfony 5.4, use method or constructor injection in your controller instead
  126.      */
  127.     protected function get(string $id): object
  128.     {
  129.         trigger_deprecation('symfony/framework-bundle''5.4''Method "%s()" is deprecated, use method or constructor injection in your controller instead.'__METHOD__);
  130.         return $this->container->get($id);
  131.     }
  132.     protected function get2(string $id): object
  133.     {
  134.         
  135.         trigger_deprecation('symfony/framework-bundle''5.4''Method "%s()" is deprecated, use method or constructor injection in your controller instead.'__METHOD__);
  136.         return $this->container2->get($id);
  137.     }
  138.     /**
  139.      * Generates a URL from the given parameters.
  140.      *
  141.      * @see UrlGeneratorInterface
  142.      */
  143.     protected function generateUrl(string $route, array $parameters = [], int $referenceType UrlGeneratorInterface::ABSOLUTE_PATH): string
  144.     {
  145.         return $this->container->get('router')->generate($route$parameters$referenceType);
  146.     }
  147.     /**
  148.      * Forwards the request to another controller.
  149.      *
  150.      * @param string $controller The controller name (a string like Bundle\BlogBundle\Controller\PostController::indexAction)
  151.      */
  152.     protected function forward(string $controller, array $path = [], array $query = []): Response
  153.     {
  154.         $request $this->container->get('request_stack')->getCurrentRequest();
  155.         $path['_controller'] = $controller;
  156.         $subRequest $request->duplicate($querynull$path);
  157.         return $this->container->get('http_kernel')->handle($subRequestHttpKernelInterface::SUB_REQUEST);
  158.     }
  159.     /**
  160.      * Returns a RedirectResponse to the given URL.
  161.      */
  162.     protected function redirect(string $urlint $status 302): RedirectResponse
  163.     {
  164.         return new RedirectResponse($url$status);
  165.     }
  166.     /**
  167.      * Returns a RedirectResponse to the given route with the given parameters.
  168.      */
  169.     protected function redirectToRoute(string $route, array $parameters = [], int $status 302): RedirectResponse
  170.     {
  171.         return $this->redirect($this->generateUrl($route$parameters), $status);
  172.     }
  173.     /**
  174.      * Returns a JsonResponse that uses the serializer component if enabled, or json_encode.
  175.      */
  176.     protected function json($dataint $status 200, array $headers = [], array $context = []): JsonResponse
  177.     {
  178.         if ($this->container->has('serializer')) {
  179.             $json $this->container->get('serializer')->serialize($data'json'array_merge([
  180.                 'json_encode_options' => JsonResponse::DEFAULT_ENCODING_OPTIONS,
  181.             ], $context));
  182.             return new JsonResponse($json$status$headerstrue);
  183.         }
  184.         return new JsonResponse($data$status$headers);
  185.     }
  186.     /**
  187.      * Returns a BinaryFileResponse object with original or customized file name and disposition header.
  188.      *
  189.      * @param \SplFileInfo|string $file File object or path to file to be sent as response
  190.      */
  191.     protected function file($filestring $fileName nullstring $disposition ResponseHeaderBag::DISPOSITION_ATTACHMENT): BinaryFileResponse
  192.     {
  193.         $response = new BinaryFileResponse($file);
  194.         $response->setContentDisposition($dispositionnull === $fileName $response->getFile()->getFilename() : $fileName);
  195.         return $response;
  196.     }
  197.     /**
  198.      * Adds a flash message to the current session for type.
  199.      *
  200.      * @throws \LogicException
  201.      */
  202.     protected function addFlash(string $type$message): void
  203.     {
  204.         try {
  205.             $this->container->get('request_stack')->getSession()->getFlashBag()->add($type$message);
  206.         } catch (SessionNotFoundException $e) {
  207.             throw new \LogicException('You cannot use the addFlash method if sessions are disabled. Enable them in "config/packages/framework.yaml".'0$e);
  208.         }
  209.     }
  210.     /**
  211.      * Checks if the attribute is granted against the current authentication token and optionally supplied subject.
  212.      *
  213.      * @throws \LogicException
  214.      */
  215.     protected function isGranted($attribute$subject null): bool
  216.     {
  217.         if (!$this->container->has('security.authorization_checker')) {
  218.             throw new \LogicException('The SecurityBundle is not registered in your application. Try running "composer require symfony/security-bundle".');
  219.         }
  220.         return $this->container->get('security.authorization_checker')->isGranted($attribute$subject);
  221.     }
  222.     /**
  223.      * Throws an exception unless the attribute is granted against the current authentication token and optionally
  224.      * supplied subject.
  225.      *
  226.      * @throws AccessDeniedException
  227.      */
  228.     protected function denyAccessUnlessGranted($attribute$subject nullstring $message 'Access Denied.'): void
  229.     {
  230.         if (!$this->isGranted($attribute$subject)) {
  231.             $exception $this->createAccessDeniedException($message);
  232.             $exception->setAttributes([$attribute]);
  233.             $exception->setSubject($subject);
  234.             throw $exception;
  235.         }
  236.     }
  237.     /**
  238.      * Returns a rendered view.
  239.      */
  240.     protected function renderView(string $view, array $parameters = []): string
  241.     {
  242.         if (!$this->container->has('twig')) {
  243.             throw new \LogicException('You cannot use the "renderView" method if the Twig Bundle is 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.     protected function render(string $view, array $parameters = [], Response $response null): Response
  251.     {
  252.         $content $this->renderView($view$parameters);
  253.         if (null === $response) {
  254.             $response = new Response();
  255.         }
  256.         $response->setContent($content);
  257.         return $response;
  258.     }
  259.     /**
  260.      * Renders a view and sets the appropriate status code when a form is listed in parameters.
  261.      *
  262.      * If an invalid form is found in the list of parameters, a 422 status code is returned.
  263.      */
  264.     protected function renderForm(string $view, array $parameters = [], Response $response null): Response
  265.     {
  266.         if (null === $response) {
  267.             $response = new Response();
  268.         }
  269.         foreach ($parameters as $k => $v) {
  270.             if ($v instanceof FormView) {
  271.                 throw new \LogicException(sprintf('Passing a FormView to "%s::renderForm()" is not supported, pass directly the form instead for parameter "%s".'get_debug_type($this), $k));
  272.             }
  273.             if (!$v instanceof FormInterface) {
  274.                 continue;
  275.             }
  276.             $parameters[$k] = $v->createView();
  277.             if (200 === $response->getStatusCode() && $v->isSubmitted() && !$v->isValid()) {
  278.                 $response->setStatusCode(422);
  279.             }
  280.         }
  281.         return $this->render($view$parameters$response);
  282.     }
  283.     /**
  284.      * Streams a view.
  285.      */
  286.     protected function stream(string $view, array $parameters = [], StreamedResponse $response null): StreamedResponse
  287.     {
  288.         if (!$this->container->has('twig')) {
  289.             throw new \LogicException('You cannot use the "stream" method if the Twig Bundle is not available. Try running "composer require symfony/twig-bundle".');
  290.         }
  291.         $twig $this->container->get('twig');
  292.         $callback = function () use ($twig$view$parameters) {
  293.             $twig->display($view$parameters);
  294.         };
  295.         if (null === $response) {
  296.             return new StreamedResponse($callback);
  297.         }
  298.         $response->setCallback($callback);
  299.         return $response;
  300.     }
  301.     /**
  302.      * Returns a NotFoundHttpException.
  303.      *
  304.      * This will result in a 404 response code. Usage example:
  305.      *
  306.      *     throw $this->createNotFoundException('Page not found!');
  307.      */
  308.     protected function createNotFoundException(string $message 'Not Found'\Throwable $previous null): NotFoundHttpException
  309.     {
  310.         return new NotFoundHttpException($message$previous);
  311.     }
  312.     /**
  313.      * Returns an AccessDeniedException.
  314.      *
  315.      * This will result in a 403 response code. Usage example:
  316.      *
  317.      *     throw $this->createAccessDeniedException('Unable to access this page!');
  318.      *
  319.      * @throws \LogicException If the Security component is not available
  320.      */
  321.     protected function createAccessDeniedException(string $message 'Access Denied.'\Throwable $previous null): AccessDeniedException
  322.     {
  323.         if (!class_exists(AccessDeniedException::class)) {
  324.             throw new \LogicException('You cannot use the "createAccessDeniedException" method if the Security component is not available. Try running "composer require symfony/security-bundle".');
  325.         }
  326.         return new AccessDeniedException($message$previous);
  327.     }
  328.     /**
  329.      * Creates and returns a Form instance from the type of the form.
  330.      */
  331.     protected function createForm(string $type$data null, array $options = []): FormInterface
  332.     {
  333.         return $this->container->get('form.factory')->create($type$data$options);
  334.     }
  335.     /**
  336.      * Creates and returns a form builder instance.
  337.      */
  338.     protected function createFormBuilder($data null, array $options = []): FormBuilderInterface
  339.     {
  340.         return $this->container->get('form.factory')->createBuilder(FormType::class, $data$options);
  341.     }
  342.     /**
  343.      * Shortcut to return the Doctrine Registry service.
  344.      *
  345.      * @throws \LogicException If DoctrineBundle is not available
  346.      *
  347.      * @deprecated since Symfony 5.4, inject an instance of ManagerRegistry in your controller instead
  348.      */
  349.     protected function getDoctrine(): ManagerRegistry
  350.     {
  351.         trigger_deprecation('symfony/framework-bundle''5.4''Method "%s()" is deprecated, inject an instance of ManagerRegistry in your controller instead.'__METHOD__);
  352.         if (!$this->container->has('doctrine')) {
  353.             throw new \LogicException('The DoctrineBundle is not registered in your application. Try running "composer require symfony/orm-pack".');
  354.         }
  355.         return $this->container->get('doctrine');
  356.     }
  357.     /**
  358.      * Get a user from the Security Token Storage.
  359.      *
  360.      * @return UserInterface|null
  361.      *
  362.      * @throws \LogicException If SecurityBundle is not available
  363.      *
  364.      * @see TokenInterface::getUser()
  365.      */
  366.     protected function getUser()
  367.     {
  368.         if (!$this->container->has('security.token_storage')) {
  369.             throw new \LogicException('The SecurityBundle is not registered in your application. Try running "composer require symfony/security-bundle".');
  370.         }
  371.         if (null === $token $this->container->get('security.token_storage')->getToken()) {
  372.             return null;
  373.         }
  374.         // @deprecated since 5.4, $user will always be a UserInterface instance
  375.         if (!\is_object($user $token->getUser())) {
  376.             // e.g. anonymous authentication
  377.             return null;
  378.         }
  379.         return $user;
  380.     }
  381.     /**
  382.      * Checks the validity of a CSRF token.
  383.      *
  384.      * @param string      $id    The id used when generating the token
  385.      * @param string|null $token The actual token sent with the request that should be validated
  386.      */
  387.     protected function isCsrfTokenValid(string $id, ?string $token): bool
  388.     {
  389.         if (!$this->container->has('security.csrf.token_manager')) {
  390.             throw new \LogicException('CSRF protection is not enabled in your application. Enable it with the "csrf_protection" key in "config/packages/framework.yaml".');
  391.         }
  392.         return $this->container->get('security.csrf.token_manager')->isTokenValid(new CsrfToken($id$token));
  393.     }
  394.     /**
  395.      * Dispatches a message to the bus.
  396.      *
  397.      * @param object|Envelope $message The message or the message pre-wrapped in an envelope
  398.      *
  399.      * @deprecated since Symfony 5.4, inject an instance of MessageBusInterface in your controller instead
  400.      */
  401.     protected function dispatchMessage(object $message, array $stamps = []): Envelope
  402.     {
  403.         trigger_deprecation('symfony/framework-bundle''5.4''Method "%s()" is deprecated, inject an instance of MessageBusInterface in your controller instead.'__METHOD__);
  404.         if (!$this->container->has('messenger.default_bus')) {
  405.             $message class_exists(Envelope::class) ? 'You need to define the "messenger.default_bus" configuration option.' 'Try running "composer require symfony/messenger".';
  406.             throw new \LogicException('The message bus is not enabled in your application. '.$message);
  407.         }
  408.         return $this->container->get('messenger.default_bus')->dispatch($message$stamps);
  409.     }
  410.     /**
  411.      * Adds a Link HTTP header to the current response.
  412.      *
  413.      * @see https://tools.ietf.org/html/rfc5988
  414.      */
  415.     protected function addLink(Request $requestLinkInterface $link): void
  416.     {
  417.         if (!class_exists(AddLinkHeaderListener::class)) {
  418.             throw new \LogicException('You cannot use the "addLink" method if the WebLink component is not available. Try running "composer require symfony/web-link".');
  419.         }
  420.         if (null === $linkProvider $request->attributes->get('_links')) {
  421.             $request->attributes->set('_links', new GenericLinkProvider([$link]));
  422.             return;
  423.         }
  424.         $request->attributes->set('_links'$linkProvider->withLink($link));
  425.     }
  426. }