Controller.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422
  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\Bundle\DoctrineBundle\Registry;
  12. use Symfony\Component\DependencyInjection\ContainerAware;
  13. use Symfony\Component\Form\Form;
  14. use Symfony\Component\Form\FormBuilder;
  15. use Symfony\Component\Form\FormTypeInterface;
  16. use Symfony\Component\HttpFoundation\RedirectResponse;
  17. use Symfony\Component\HttpFoundation\Request;
  18. use Symfony\Component\HttpFoundation\Response;
  19. use Symfony\Component\HttpFoundation\StreamedResponse;
  20. use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
  21. use Symfony\Component\HttpKernel\HttpKernelInterface;
  22. use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
  23. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  24. use Symfony\Component\Security\Core\Exception\AccessDeniedException;
  25. use Symfony\Component\Security\Csrf\CsrfToken;
  26. /**
  27. * Controller is a simple implementation of a Controller.
  28. *
  29. * It provides methods to common features needed in controllers.
  30. *
  31. * @author Fabien Potencier <fabien@symfony.com>
  32. */
  33. class Controller extends ContainerAware
  34. {
  35. /**
  36. * Generates a URL from the given parameters.
  37. *
  38. * @param string $route The name of the route
  39. * @param mixed $parameters An array of parameters
  40. * @param int $referenceType The type of reference (one of the constants in UrlGeneratorInterface)
  41. *
  42. * @return string The generated URL
  43. *
  44. * @see UrlGeneratorInterface
  45. */
  46. public function generateUrl($route, $parameters = array(), $referenceType = UrlGeneratorInterface::ABSOLUTE_PATH)
  47. {
  48. return $this->container->get('router')->generate($route, $parameters, $referenceType);
  49. }
  50. /**
  51. * Forwards the request to another controller.
  52. *
  53. * @param string $controller The controller name (a string like BlogBundle:Post:index)
  54. * @param array $path An array of path parameters
  55. * @param array $query An array of query parameters
  56. *
  57. * @return Response A Response instance
  58. */
  59. public function forward($controller, array $path = array(), array $query = array())
  60. {
  61. $path['_controller'] = $controller;
  62. $subRequest = $this->container->get('request_stack')->getCurrentRequest()->duplicate($query, null, $path);
  63. return $this->container->get('http_kernel')->handle($subRequest, HttpKernelInterface::SUB_REQUEST);
  64. }
  65. /**
  66. * Returns a RedirectResponse to the given URL.
  67. *
  68. * @param string $url The URL to redirect to
  69. * @param int $status The status code to use for the Response
  70. *
  71. * @return RedirectResponse
  72. */
  73. public function redirect($url, $status = 302)
  74. {
  75. return new RedirectResponse($url, $status);
  76. }
  77. /**
  78. * Returns a RedirectResponse to the given route with the given parameters.
  79. *
  80. * @param string $route The name of the route
  81. * @param array $parameters An array of parameters
  82. * @param int $status The status code to use for the Response
  83. *
  84. * @return RedirectResponse
  85. */
  86. protected function redirectToRoute($route, array $parameters = array(), $status = 302)
  87. {
  88. return $this->redirect($this->generateUrl($route, $parameters), $status);
  89. }
  90. /**
  91. * Adds a flash message to the current session for type.
  92. *
  93. * @param string $type The type
  94. * @param string $message The message
  95. *
  96. * @throws \LogicException
  97. */
  98. protected function addFlash($type, $message)
  99. {
  100. if (!$this->container->has('session')) {
  101. throw new \LogicException('You can not use the addFlash method if sessions are disabled.');
  102. }
  103. $this->container->get('session')->getFlashBag()->add($type, $message);
  104. }
  105. /**
  106. * Checks if the attributes are granted against the current authentication token and optionally supplied object.
  107. *
  108. * @param mixed $attributes The attributes
  109. * @param mixed $object The object
  110. *
  111. * @return bool
  112. *
  113. * @throws \LogicException
  114. */
  115. protected function isGranted($attributes, $object = null)
  116. {
  117. if (!$this->container->has('security.authorization_checker')) {
  118. throw new \LogicException('The SecurityBundle is not registered in your application.');
  119. }
  120. return $this->container->get('security.authorization_checker')->isGranted($attributes, $object);
  121. }
  122. /**
  123. * Throws an exception unless the attributes are granted against the current authentication token and optionally
  124. * supplied object.
  125. *
  126. * @param mixed $attributes The attributes
  127. * @param mixed $object The object
  128. * @param string $message The message passed to the exception
  129. *
  130. * @throws AccessDeniedException
  131. */
  132. protected function denyAccessUnlessGranted($attributes, $object = null, $message = 'Access Denied.')
  133. {
  134. if (!$this->isGranted($attributes, $object)) {
  135. throw $this->createAccessDeniedException($message);
  136. }
  137. }
  138. /**
  139. * Returns a rendered view.
  140. *
  141. * @param string $view The view name
  142. * @param array $parameters An array of parameters to pass to the view
  143. *
  144. * @return string The rendered view
  145. */
  146. public function renderView($view, array $parameters = array())
  147. {
  148. if ($this->container->has('templating')) {
  149. return $this->container->get('templating')->render($view, $parameters);
  150. }
  151. if (!$this->container->has('twig')) {
  152. throw new \LogicException('You can not use the "renderView" method if the Templating Component or the Twig Bundle are not available.');
  153. }
  154. return $this->container->get('twig')->render($view, $parameters);
  155. }
  156. /**
  157. * Renders a view.
  158. *
  159. * @param string $view The view name
  160. * @param array $parameters An array of parameters to pass to the view
  161. * @param Response $response A response instance
  162. *
  163. * @return Response A Response instance
  164. */
  165. public function render($view, array $parameters = array(), Response $response = null)
  166. {
  167. if ($this->container->has('templating')) {
  168. return $this->container->get('templating')->renderResponse($view, $parameters, $response);
  169. }
  170. if (!$this->container->has('twig')) {
  171. throw new \LogicException('You can not use the "render" method if the Templating Component or the Twig Bundle are not available.');
  172. }
  173. if (null === $response) {
  174. $response = new Response();
  175. }
  176. $response->setContent($this->container->get('twig')->render($view, $parameters));
  177. return $response;
  178. }
  179. /**
  180. * Streams a view.
  181. *
  182. * @param string $view The view name
  183. * @param array $parameters An array of parameters to pass to the view
  184. * @param StreamedResponse $response A response instance
  185. *
  186. * @return StreamedResponse A StreamedResponse instance
  187. */
  188. public function stream($view, array $parameters = array(), StreamedResponse $response = null)
  189. {
  190. if ($this->container->has('templating')) {
  191. $templating = $this->container->get('templating');
  192. $callback = function () use ($templating, $view, $parameters) {
  193. $templating->stream($view, $parameters);
  194. };
  195. } elseif ($this->container->has('twig')) {
  196. $twig = $this->container->get('twig');
  197. $callback = function () use ($twig, $view, $parameters) {
  198. $twig->display($view, $parameters);
  199. };
  200. } else {
  201. throw new \LogicException('You can not use the "stream" method if the Templating Component or the Twig Bundle are not available.');
  202. }
  203. if (null === $response) {
  204. return new StreamedResponse($callback);
  205. }
  206. $response->setCallback($callback);
  207. return $response;
  208. }
  209. /**
  210. * Returns a NotFoundHttpException.
  211. *
  212. * This will result in a 404 response code. Usage example:
  213. *
  214. * throw $this->createNotFoundException('Page not found!');
  215. *
  216. * @param string $message A message
  217. * @param \Exception|null $previous The previous exception
  218. *
  219. * @return NotFoundHttpException
  220. */
  221. public function createNotFoundException($message = 'Not Found', \Exception $previous = null)
  222. {
  223. return new NotFoundHttpException($message, $previous);
  224. }
  225. /**
  226. * Returns an AccessDeniedException.
  227. *
  228. * This will result in a 403 response code. Usage example:
  229. *
  230. * throw $this->createAccessDeniedException('Unable to access this page!');
  231. *
  232. * @param string $message A message
  233. * @param \Exception|null $previous The previous exception
  234. *
  235. * @return AccessDeniedException
  236. */
  237. public function createAccessDeniedException($message = 'Access Denied.', \Exception $previous = null)
  238. {
  239. return new AccessDeniedException($message, $previous);
  240. }
  241. /**
  242. * Creates and returns a Form instance from the type of the form.
  243. *
  244. * @param string|FormTypeInterface $type The built type of the form
  245. * @param mixed $data The initial data for the form
  246. * @param array $options Options for the form
  247. *
  248. * @return Form
  249. */
  250. public function createForm($type, $data = null, array $options = array())
  251. {
  252. return $this->container->get('form.factory')->create($type, $data, $options);
  253. }
  254. /**
  255. * Creates and returns a form builder instance.
  256. *
  257. * @param mixed $data The initial data for the form
  258. * @param array $options Options for the form
  259. *
  260. * @return FormBuilder
  261. */
  262. public function createFormBuilder($data = null, array $options = array())
  263. {
  264. if (method_exists('Symfony\Component\Form\AbstractType', 'getBlockPrefix')) {
  265. $type = 'Symfony\Component\Form\Extension\Core\Type\FormType';
  266. } else {
  267. // not using the class name is deprecated since Symfony 2.8 and
  268. // is only used for backwards compatibility with older versions
  269. // of the Form component
  270. $type = 'form';
  271. }
  272. return $this->container->get('form.factory')->createBuilder($type, $data, $options);
  273. }
  274. /**
  275. * Shortcut to return the request service.
  276. *
  277. * @return Request
  278. *
  279. * @deprecated since version 2.4, to be removed in 3.0.
  280. * Ask Symfony to inject the Request object into your controller
  281. * method instead by type hinting it in the method's signature.
  282. */
  283. public function getRequest()
  284. {
  285. @trigger_error('The '.__METHOD__.' method is deprecated since Symfony 2.4 and will be removed in 3.0. The only reliable way to get the "Request" object is to inject it in the action method.', E_USER_DEPRECATED);
  286. return $this->container->get('request_stack')->getCurrentRequest();
  287. }
  288. /**
  289. * Shortcut to return the Doctrine Registry service.
  290. *
  291. * @return Registry
  292. *
  293. * @throws \LogicException If DoctrineBundle is not available
  294. */
  295. public function getDoctrine()
  296. {
  297. if (!$this->container->has('doctrine')) {
  298. throw new \LogicException('The DoctrineBundle is not registered in your application.');
  299. }
  300. return $this->container->get('doctrine');
  301. }
  302. /**
  303. * Get a user from the Security Token Storage.
  304. *
  305. * @return mixed
  306. *
  307. * @throws \LogicException If SecurityBundle is not available
  308. *
  309. * @see TokenInterface::getUser()
  310. */
  311. public function getUser()
  312. {
  313. if (!$this->container->has('security.token_storage')) {
  314. throw new \LogicException('The SecurityBundle is not registered in your application.');
  315. }
  316. if (null === $token = $this->container->get('security.token_storage')->getToken()) {
  317. return;
  318. }
  319. if (!\is_object($user = $token->getUser())) {
  320. // e.g. anonymous authentication
  321. return;
  322. }
  323. return $user;
  324. }
  325. /**
  326. * Returns true if the service id is defined.
  327. *
  328. * @param string $id The service id
  329. *
  330. * @return bool true if the service id is defined, false otherwise
  331. */
  332. public function has($id)
  333. {
  334. return $this->container->has($id);
  335. }
  336. /**
  337. * Gets a container service by its id.
  338. *
  339. * @param string $id The service id
  340. *
  341. * @return object The service
  342. */
  343. public function get($id)
  344. {
  345. if ('request' === $id) {
  346. @trigger_error('The "request" service is deprecated and will be removed in 3.0. Add a typehint for Symfony\\Component\\HttpFoundation\\Request to your controller parameters to retrieve the request instead.', E_USER_DEPRECATED);
  347. }
  348. return $this->container->get($id);
  349. }
  350. /**
  351. * Gets a container configuration parameter by its name.
  352. *
  353. * @param string $name The parameter name
  354. *
  355. * @return mixed
  356. */
  357. protected function getParameter($name)
  358. {
  359. return $this->container->getParameter($name);
  360. }
  361. /**
  362. * Checks the validity of a CSRF token.
  363. *
  364. * @param string $id The id used when generating the token
  365. * @param string $token The actual token sent with the request that should be validated
  366. *
  367. * @return bool
  368. */
  369. protected function isCsrfTokenValid($id, $token)
  370. {
  371. if (!$this->container->has('security.csrf.token_manager')) {
  372. throw new \LogicException('CSRF protection is not enabled in your application.');
  373. }
  374. return $this->container->get('security.csrf.token_manager')->isTokenValid(new CsrfToken($id, $token));
  375. }
  376. }