vendor/sylius/resource-bundle/src/Bundle/Controller/ControllerTrait.php line 247

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