MongoDbSessionHandler.php 5.7KB

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