MongoDbSessionHandler.php 6.5 KB

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