RequestHelper.php 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  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\Templating\Helper;
  11. use Symfony\Component\HttpFoundation\Request;
  12. use Symfony\Component\HttpFoundation\RequestStack;
  13. use Symfony\Component\Templating\Helper\Helper;
  14. /**
  15. * RequestHelper provides access to the current request parameters.
  16. *
  17. * @author Fabien Potencier <fabien@symfony.com>
  18. */
  19. class RequestHelper extends Helper
  20. {
  21. protected $request;
  22. protected $requestStack;
  23. /**
  24. * @param Request|RequestStack $requestStack A RequestStack instance or a Request instance
  25. *
  26. * @deprecated since version 2.5, passing a Request instance is deprecated and support for it will be removed in 3.0.
  27. */
  28. public function __construct($requestStack)
  29. {
  30. if ($requestStack instanceof Request) {
  31. @trigger_error('Since version 2.5, passing a Request instance into the '.__METHOD__.' is deprecated and support for it will be removed in 3.0. Inject a Symfony\Component\HttpFoundation\RequestStack instance instead.', E_USER_DEPRECATED);
  32. $this->request = $requestStack;
  33. } elseif ($requestStack instanceof RequestStack) {
  34. $this->requestStack = $requestStack;
  35. } else {
  36. throw new \InvalidArgumentException('RequestHelper only accepts a Request or a RequestStack instance.');
  37. }
  38. }
  39. /**
  40. * Returns a parameter from the current request object.
  41. *
  42. * @param string $key The name of the parameter
  43. * @param string $default A default value
  44. *
  45. * @return mixed
  46. *
  47. * @see Request::get()
  48. */
  49. public function getParameter($key, $default = null)
  50. {
  51. return $this->getRequest()->get($key, $default);
  52. }
  53. /**
  54. * Returns the locale.
  55. *
  56. * @return string
  57. */
  58. public function getLocale()
  59. {
  60. return $this->getRequest()->getLocale();
  61. }
  62. private function getRequest()
  63. {
  64. if ($this->requestStack) {
  65. if (!$this->requestStack->getCurrentRequest()) {
  66. throw new \LogicException('A Request must be available.');
  67. }
  68. return $this->requestStack->getCurrentRequest();
  69. }
  70. return $this->request;
  71. }
  72. /**
  73. * {@inheritdoc}
  74. */
  75. public function getName()
  76. {
  77. return 'request';
  78. }
  79. }