WriteSafeSessionHandler.php 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. <?php
  2. namespace Drupal\Core\Session;
  3. /**
  4. * Wraps another SessionHandlerInterface to prevent writes when not allowed.
  5. */
  6. class WriteSafeSessionHandler implements \SessionHandlerInterface, WriteSafeSessionHandlerInterface {
  7. /**
  8. * @var \SessionHandlerInterface
  9. */
  10. protected $wrappedSessionHandler;
  11. /**
  12. * Whether or not the session is enabled for writing.
  13. *
  14. * @var bool
  15. */
  16. protected $sessionWritable;
  17. /**
  18. * Constructs a new write safe session handler.
  19. *
  20. * @param \SessionHandlerInterface $wrapped_session_handler
  21. * The underlying session handler.
  22. * @param bool $session_writable
  23. * Whether or not the session should be initially writable.
  24. */
  25. public function __construct(\SessionHandlerInterface $wrapped_session_handler, $session_writable = TRUE) {
  26. $this->wrappedSessionHandler = $wrapped_session_handler;
  27. $this->sessionWritable = $session_writable;
  28. }
  29. /**
  30. * {@inheritdoc}
  31. */
  32. public function close() {
  33. return $this->wrappedSessionHandler->close();
  34. }
  35. /**
  36. * {@inheritdoc}
  37. */
  38. public function destroy($session_id) {
  39. return $this->wrappedSessionHandler->destroy($session_id);
  40. }
  41. /**
  42. * {@inheritdoc}
  43. */
  44. public function gc($max_lifetime) {
  45. return $this->wrappedSessionHandler->gc($max_lifetime);
  46. }
  47. /**
  48. * {@inheritdoc}
  49. */
  50. public function open($save_path, $session_id) {
  51. return $this->wrappedSessionHandler->open($save_path, $session_id);
  52. }
  53. /**
  54. * {@inheritdoc}
  55. */
  56. public function read($session_id) {
  57. return $this->wrappedSessionHandler->read($session_id);
  58. }
  59. /**
  60. * {@inheritdoc}
  61. */
  62. public function write($session_id, $session_data) {
  63. if ($this->isSessionWritable()) {
  64. return $this->wrappedSessionHandler->write($session_id, $session_data);
  65. }
  66. else {
  67. return TRUE;
  68. }
  69. }
  70. /**
  71. * {@inheritdoc}
  72. */
  73. public function setSessionWritable($flag) {
  74. $this->sessionWritable = (bool) $flag;
  75. }
  76. /**
  77. * {@inheritdoc}
  78. */
  79. public function isSessionWritable() {
  80. return $this->sessionWritable;
  81. }
  82. }