CookieSessionHandler.php 2.4KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122
  1. <?php
  2. namespace Illuminate\Session;
  3. use SessionHandlerInterface;
  4. use Illuminate\Support\InteractsWithTime;
  5. use Symfony\Component\HttpFoundation\Request;
  6. use Illuminate\Contracts\Cookie\QueueingFactory as CookieJar;
  7. class CookieSessionHandler implements SessionHandlerInterface
  8. {
  9. use InteractsWithTime;
  10. /**
  11. * The cookie jar instance.
  12. *
  13. * @var \Illuminate\Contracts\Cookie\Factory
  14. */
  15. protected $cookie;
  16. /**
  17. * The request instance.
  18. *
  19. * @var \Symfony\Component\HttpFoundation\Request
  20. */
  21. protected $request;
  22. /**
  23. * The number of minutes the session should be valid.
  24. *
  25. * @var int
  26. */
  27. protected $minutes;
  28. /**
  29. * Create a new cookie driven handler instance.
  30. *
  31. * @param \Illuminate\Contracts\Cookie\QueueingFactory $cookie
  32. * @param int $minutes
  33. * @return void
  34. */
  35. public function __construct(CookieJar $cookie, $minutes)
  36. {
  37. $this->cookie = $cookie;
  38. $this->minutes = $minutes;
  39. }
  40. /**
  41. * {@inheritdoc}
  42. */
  43. public function open($savePath, $sessionName)
  44. {
  45. return true;
  46. }
  47. /**
  48. * {@inheritdoc}
  49. */
  50. public function close()
  51. {
  52. return true;
  53. }
  54. /**
  55. * {@inheritdoc}
  56. */
  57. public function read($sessionId)
  58. {
  59. $value = $this->request->cookies->get($sessionId) ?: '';
  60. if (! is_null($decoded = json_decode($value, true)) && is_array($decoded)) {
  61. if (isset($decoded['expires']) && $this->currentTime() <= $decoded['expires']) {
  62. return $decoded['data'];
  63. }
  64. }
  65. return '';
  66. }
  67. /**
  68. * {@inheritdoc}
  69. */
  70. public function write($sessionId, $data)
  71. {
  72. $this->cookie->queue($sessionId, json_encode([
  73. 'data' => $data,
  74. 'expires' => $this->availableAt($this->minutes * 60),
  75. ]), $this->minutes);
  76. return true;
  77. }
  78. /**
  79. * {@inheritdoc}
  80. */
  81. public function destroy($sessionId)
  82. {
  83. $this->cookie->queue($this->cookie->forget($sessionId));
  84. return true;
  85. }
  86. /**
  87. * {@inheritdoc}
  88. */
  89. public function gc($lifetime)
  90. {
  91. return true;
  92. }
  93. /**
  94. * Set the request instance.
  95. *
  96. * @param \Symfony\Component\HttpFoundation\Request $request
  97. * @return void
  98. */
  99. public function setRequest(Request $request)
  100. {
  101. $this->request = $request;
  102. }
  103. }