1: <?php
2:
3: 4: 5: 6: 7: 8: 9: 10:
11:
12: namespace Symfony\Component\HttpFoundation\Session\Storage\Handler;
13:
14: 15: 16: 17: 18:
19: class MongoDbSessionHandler implements \SessionHandlerInterface
20: {
21: 22: 23:
24: private $mongo;
25:
26: 27: 28:
29: private $collection;
30:
31: 32: 33:
34: private $options;
35:
36: 37: 38: 39: 40: 41: 42: 43: 44: 45: 46: 47: 48: 49: 50: 51:
52: public function __construct($mongo, array $options)
53: {
54: if (!($mongo instanceof \MongoClient || $mongo instanceof \Mongo)) {
55: throw new \InvalidArgumentException('MongoClient or Mongo instance required');
56: }
57:
58: if (!isset($options['database']) || !isset($options['collection'])) {
59: throw new \InvalidArgumentException('You must provide the "database" and "collection" option for MongoDBSessionHandler');
60: }
61:
62: $this->mongo = $mongo;
63:
64: $this->options = array_merge(array(
65: 'id_field' => '_id',
66: 'data_field' => 'data',
67: 'time_field' => 'time',
68: ), $options);
69: }
70:
71: 72: 73:
74: public function open($savePath, $sessionName)
75: {
76: return true;
77: }
78:
79: 80: 81:
82: public function close()
83: {
84: return true;
85: }
86:
87: 88: 89:
90: public function destroy($sessionId)
91: {
92: $this->getCollection()->remove(array(
93: $this->options['id_field'] => $sessionId
94: ));
95:
96: return true;
97: }
98:
99: 100: 101:
102: public function gc($lifetime)
103: {
104: 105: 106: 107: 108: 109: 110: 111:
112: $time = new \MongoDate(time() - $lifetime);
113:
114: $this->getCollection()->remove(array(
115: $this->options['time_field'] => array('$lt' => $time),
116: ));
117:
118: return true;
119: }
120:
121: 122: 123:
124: public function write($sessionId, $data)
125: {
126: $this->getCollection()->update(
127: array($this->options['id_field'] => $sessionId),
128: array('$set' => array(
129: $this->options['data_field'] => new \MongoBinData($data, \MongoBinData::BYTE_ARRAY),
130: $this->options['time_field'] => new \MongoDate(),
131: )),
132: array('upsert' => true, 'multiple' => false)
133: );
134:
135: return true;
136: }
137:
138: 139: 140:
141: public function read($sessionId)
142: {
143: $dbData = $this->getCollection()->findOne(array(
144: $this->options['id_field'] => $sessionId,
145: ));
146:
147: return null === $dbData ? '' : $dbData[$this->options['data_field']]->bin;
148: }
149:
150: 151: 152: 153: 154:
155: private function getCollection()
156: {
157: if (null === $this->collection) {
158: $this->collection = $this->mongo->selectCollection($this->options['database'], $this->options['collection']);
159: }
160:
161: return $this->collection;
162: }
163: }
164: