MongoDbSessionHandler.php 4.9 KB

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