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

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