MongoDbSessionHandler.php 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193
  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\Component\HttpFoundation\Session\Storage\Handler;
  11. use MongoDB\BSON\Binary;
  12. use MongoDB\BSON\UTCDateTime;
  13. use MongoDB\Client;
  14. use MongoDB\Collection;
  15. /**
  16. * Session handler using the mongodb/mongodb package and MongoDB driver extension.
  17. *
  18. * @author Markus Bachmann <markus.bachmann@bachi.biz>
  19. *
  20. * @see https://packagist.org/packages/mongodb/mongodb
  21. * @see https://php.net/mongodb
  22. */
  23. class MongoDbSessionHandler extends AbstractSessionHandler
  24. {
  25. private $mongo;
  26. /**
  27. * @var Collection
  28. */
  29. private $collection;
  30. /**
  31. * @var array
  32. */
  33. private $options;
  34. /**
  35. * Constructor.
  36. *
  37. * List of available options:
  38. * * database: The name of the database [required]
  39. * * collection: The name of the collection [required]
  40. * * id_field: The field name for storing the session id [default: _id]
  41. * * data_field: The field name for storing the session data [default: data]
  42. * * time_field: The field name for storing the timestamp [default: time]
  43. * * expiry_field: The field name for storing the expiry-timestamp [default: expires_at].
  44. *
  45. * It is strongly recommended to put an index on the `expiry_field` for
  46. * garbage-collection. Alternatively it's possible to automatically expire
  47. * the sessions in the database as described below:
  48. *
  49. * A TTL collections can be used on MongoDB 2.2+ to cleanup expired sessions
  50. * automatically. Such an index can for example look like this:
  51. *
  52. * db.<session-collection>.createIndex(
  53. * { "<expiry-field>": 1 },
  54. * { "expireAfterSeconds": 0 }
  55. * )
  56. *
  57. * More details on: https://docs.mongodb.org/manual/tutorial/expire-data/
  58. *
  59. * If you use such an index, you can drop `gc_probability` to 0 since
  60. * no garbage-collection is required.
  61. *
  62. * @throws \InvalidArgumentException When "database" or "collection" not provided
  63. */
  64. public function __construct(Client $mongo, array $options)
  65. {
  66. if (!isset($options['database']) || !isset($options['collection'])) {
  67. throw new \InvalidArgumentException('You must provide the "database" and "collection" option for MongoDBSessionHandler.');
  68. }
  69. $this->mongo = $mongo;
  70. $this->options = array_merge([
  71. 'id_field' => '_id',
  72. 'data_field' => 'data',
  73. 'time_field' => 'time',
  74. 'expiry_field' => 'expires_at',
  75. ], $options);
  76. }
  77. /**
  78. * @return bool
  79. */
  80. #[\ReturnTypeWillChange]
  81. public function close()
  82. {
  83. return true;
  84. }
  85. /**
  86. * {@inheritdoc}
  87. */
  88. protected function doDestroy(string $sessionId)
  89. {
  90. $this->getCollection()->deleteOne([
  91. $this->options['id_field'] => $sessionId,
  92. ]);
  93. return true;
  94. }
  95. /**
  96. * @return int|false
  97. */
  98. #[\ReturnTypeWillChange]
  99. public function gc($maxlifetime)
  100. {
  101. return $this->getCollection()->deleteMany([
  102. $this->options['expiry_field'] => ['$lt' => new UTCDateTime()],
  103. ])->getDeletedCount();
  104. }
  105. /**
  106. * {@inheritdoc}
  107. */
  108. protected function doWrite(string $sessionId, string $data)
  109. {
  110. $expiry = new UTCDateTime((time() + (int) ini_get('session.gc_maxlifetime')) * 1000);
  111. $fields = [
  112. $this->options['time_field'] => new UTCDateTime(),
  113. $this->options['expiry_field'] => $expiry,
  114. $this->options['data_field'] => new Binary($data, Binary::TYPE_OLD_BINARY),
  115. ];
  116. $this->getCollection()->updateOne(
  117. [$this->options['id_field'] => $sessionId],
  118. ['$set' => $fields],
  119. ['upsert' => true]
  120. );
  121. return true;
  122. }
  123. /**
  124. * @return bool
  125. */
  126. #[\ReturnTypeWillChange]
  127. public function updateTimestamp($sessionId, $data)
  128. {
  129. $expiry = new UTCDateTime((time() + (int) ini_get('session.gc_maxlifetime')) * 1000);
  130. $this->getCollection()->updateOne(
  131. [$this->options['id_field'] => $sessionId],
  132. ['$set' => [
  133. $this->options['time_field'] => new UTCDateTime(),
  134. $this->options['expiry_field'] => $expiry,
  135. ]]
  136. );
  137. return true;
  138. }
  139. /**
  140. * {@inheritdoc}
  141. */
  142. protected function doRead(string $sessionId)
  143. {
  144. $dbData = $this->getCollection()->findOne([
  145. $this->options['id_field'] => $sessionId,
  146. $this->options['expiry_field'] => ['$gte' => new UTCDateTime()],
  147. ]);
  148. if (null === $dbData) {
  149. return '';
  150. }
  151. return $dbData[$this->options['data_field']]->getData();
  152. }
  153. private function getCollection(): Collection
  154. {
  155. if (null === $this->collection) {
  156. $this->collection = $this->mongo->selectCollection($this->options['database'], $this->options['collection']);
  157. }
  158. return $this->collection;
  159. }
  160. /**
  161. * @return Client
  162. */
  163. protected function getMongo()
  164. {
  165. return $this->mongo;
  166. }
  167. }