菜谱项目

MongoDbSessionHandler.php 6.5KB

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