SessionHelper.php 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  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. * SessionHelper provides read-only access to the session attributes.
  16. *
  17. * @author Fabien Potencier <fabien@symfony.com>
  18. */
  19. class SessionHelper extends Helper
  20. {
  21. protected $session;
  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->session = $requestStack->getSession();
  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 an attribute.
  41. *
  42. * @param string $name The attribute name
  43. * @param mixed $default The default value
  44. *
  45. * @return mixed
  46. */
  47. public function get($name, $default = null)
  48. {
  49. return $this->getSession()->get($name, $default);
  50. }
  51. public function getFlash($name, array $default = array())
  52. {
  53. return $this->getSession()->getFlashBag()->get($name, $default);
  54. }
  55. public function getFlashes()
  56. {
  57. return $this->getSession()->getFlashBag()->all();
  58. }
  59. public function hasFlash($name)
  60. {
  61. return $this->getSession()->getFlashBag()->has($name);
  62. }
  63. private function getSession()
  64. {
  65. if (null === $this->session) {
  66. if (!$this->requestStack->getMasterRequest()) {
  67. throw new \LogicException('A Request must be available.');
  68. }
  69. $this->session = $this->requestStack->getMasterRequest()->getSession();
  70. }
  71. return $this->session;
  72. }
  73. /**
  74. * {@inheritdoc}
  75. */
  76. public function getName()
  77. {
  78. return 'session';
  79. }
  80. }