forked from Sammaye/MongoYii
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathEMongoClient.php
339 lines (290 loc) · 8.82 KB
/
EMongoClient.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
<?php
/**
* EMongoClient
*
* The MongoDB and MongoClient class combined.
*
* Quite deceptively this classes magics actually represents the DATABASE not the connection.
*
* Normally this would represent the MongoClient or Mongo and it is even named after them and implements
* some of their functions but it is not due to the way Yii works.
*/
class EMongoClient extends CApplicationComponent{
/**
* The server string (connection string pre-1.3)
* @var string
*/
public $server;
/**
* Additional options for the connection constructor
* @var array
*/
public $options = array();
/**
* The name of the database
* @var string
*/
public $db;
/**
* Write Concern, will default to acked writes
* @see http://php.net/manual/en/mongo.writeconcerns.php
* @var int|string
*/
public $w = 1;
/**
* Are we using journaled writes here? Beware this makes all writes wait for the journal, it does not
* state whether MongoDB is using journaling. Only works 1.3+ driver
* @var boolean
*/
public $j = false;
/**
* The read preference
* The first param is the textual version of the constant name in the MongoClient for the type of read
* i.e. RP_PRIMARY and the second emulates the setReadPreference prototypes second parameter
* @see http://php.net/manual/en/mongo.readpreferences.php
* @var array()
*/
public $RP = array('RP_PRIMARY', array());
/**
* The Legacy read preference. DO NOT USE IF YOU ARE ON VERSION 1.3+
* @var boolean
*/
public $setSlaveOkay = false;
/**
* The Mongo Connection instance
* @var Mongo|MongoClient
*/
private $_mongo;
/**
* The database instance
* @var MongoDB
*/
private $_db;
/**
* Caches reflection properties for our objects so we don't have
* to keep getting them
* @var array
*/
private $_meta = array();
/**
* The default action is to get a collection
*/
public function __get($k){
$getter='get'.$k;
if(method_exists($this,$getter))
return $this->$getter();
return $this->selectCollection($k);
}
/**
* Will either call a function on the database or call for a collection
*/
public function __call($name,$parameters = array()){
if(method_exists($this->_db, $name)){
return call_user_func_array(array($this->_db, $name), $parameters);
}
}
public function __construct(){
// We copy this function to add the subdocument validator as a built in validator
CValidator::$builtInValidators['subdocument'] = 'ESubdocumentValidator';
}
/**
* The init function
* We also connect here
* @see yii/framework/base/CApplicationComponent::init()
*/
public function init(){
parent::init();
$this->connect();
}
/**
* Connects to our database
*/
public function connect(){
// We don't need to throw useless exceptions here, the MongoDB PHP Driver has its own checks and error reporting
// Yii will easily and effortlessly display the errors from the PHP driver, we should only catch its exceptions if
// we wanna add our own custom messages on top which we don't, the errors are quite self explanatory
if(version_compare(phpversion('mongo'), '1.3.0', '<')){
$this->_mongo = new Mongo($this->server, $this->options);
$this->_mongo->connect();
if($this->setSlaveOkay)
$this->_mongo->setSlaveOkay($this->setSlaveOkay);
}else{
$this->_mongo = new MongoClient($this->server, $this->options);
if(is_array($this->RP)){
$const = $this->RP[0];
$opts = $this->RP[1];
if(!empty($opts)) // I do this due to a bug that exists in some PHP driver versions
$this->_mongo->setReadPreference(constant('MongoClient::'.$const), $opts);
else
$this->_mongo->setReadPreference(constant('MongoClient::'.$const));
}
}
}
/**
* Gets the connection object
* @return Mongo|MongoClient
*/
public function getConnection(){
if(empty($this->_mongo))
$this->connect();
return $this->_mongo;
}
/**
* Sets the raw database adhoc
* @param $name
*/
public function setDB($name){
$this->_db = $this->getConnection()->selectDb($name);
}
/**
* Gets the raw Database
* @return MongoDB
*/
public function getDB(){
if(empty($this->_db))
$this->setDB($this->db);
return $this->_db;
}
/**
* You should never call this function.
*
* The PHP driver will handle connections automatically, and will
* keep this performant for you.
*/
public function close(){
if(!empty($this->_mongo))
$this->_mongo->close();
}
/**
* Since there is no easy definition of the public collection class without drilling down
* this function is designed to be a helper to make aggregation calling more standard.
* @param $collection
* @param $pipelines
*/
public function aggregate($collection, $pipelines){
if(version_compare(phpversion('mongo'), '1.3.0', '<')){
return $this->getDB()->command(array(
'aggregate' => $collection,
'pipeline' => $pipelines
));
}
return $this->getDB()->$collection->aggregate($pipelines);
}
/**
* Command helper
* @param array|sting $command
*/
public function command($command = array()){
return $this->getDB()->command($command);
}
/**
* ATM does nothing but the original processing; ATM
* @param $name
*/
public function selectCollection($name){
return $this->getDB()->selectCollection($name);
}
/**
* Sets the document cache for any particular document (EMongoDocument/EMongoModel)
* sent in as the first parameter of this function
* @param $o
*/
function setDocumentCache($o){
if(
$this->getDocumentCache(get_class($o))===array() && // Run reflection and cache it if not already there
(get_class($o) != 'EMongoDocument' && get_class($o) != 'EMongoModel') /* We can't cache the model */
){
$_meta = array();
$reflect = new ReflectionClass(get_class($o));
$class_vars = $reflect->getProperties(ReflectionProperty::IS_PUBLIC | ReflectionProperty::IS_PROTECTED); // Pre-defined doc attributes
foreach ($class_vars as $prop) {
if($prop->isStatic())
continue;
$docBlock = $prop->getDocComment();
$field_meta = array(
'name' => $prop->getName(),
'virtual' => $prop->isProtected() || preg_match('/@virtual/i', $docBlock) <= 0 ? false : true
);
// Lets fetch the data type for this field
// Since we always fetch the data type for this field we make a regex that will only pick out the first
if(preg_match('/@var ([a-zA-Z]+)/', $docBlock, $matches) > 0){
$field_meta['type'] = $matches[1];
}
$_meta[$prop->getName()] = $field_meta;
}
$this->_meta[get_class($o)] = $_meta;
}
}
/**
* Get a list of the fields (attributes) for a document from cache
* @param string $name
* @param boolean $include_virtual
*/
public function getFieldCache($name, $include_virtual = false){
$doc = isset($this->_meta[$name]) ? $this->_meta[$name] : array();
$fields = array();
foreach($doc as $name => $opts)
if($include_virtual || !$opts['virtual']) $fields[] = $name;
return $fields;
}
/**
* Just gets the document cache for a model
* @param string $name
* @return NULL|array
*/
public function getDocumentCache($name){
return isset($this->_meta[$name]) ? $this->_meta[$name] : array();
}
/**
* Gets the default write concern options for all queries through active record
* @return array
*/
public function getDefaultWriteConcern(){
if(version_compare(phpversion('mongo'), '1.3.0', '<')){
if($this->w == 1){
return array('safe' => true);
}elseif($this->w > 0){
return array('safe' => $this->w);
}
}else{
return array('w' => $this->w, 'j' => $this->j);
}
return array();
}
/**
* Create ObjectId from timestamp. This function is not actively used it is
* here as a helper for anyone who needs it
* @param $yourTimestamp
*/
public function createMongoIdFromTimestamp( $yourTimestamp )
{
static $inc = 0;
$ts = pack( 'N', $yourTimestamp );
$m = substr( md5( gethostname()), 0, 3 );
$pid = pack( 'n', posix_getpid() );
$trail = substr( pack( 'N', $inc++ ), 1, 3);
$bin = sprintf("%s%s%s%s", $ts, $m, $pid, $trail);
$id = '';
for ($i = 0; $i < 12; $i++ )
{
$id .= sprintf("%02X", ord($bin[$i]));
}
return new MongoID($id);
}
/**
* Set read preference on MongoClient
* @param $pref
* @param $options
*/
public function setReadPreference($pref, $options=array()){
return $this->getConnection()->setReadPreference($pref, $options);
}
/**
* setSlaveOkay on Mongo
* @param $bool
*/
public function setSlaveOkay($bool){
return $this->getConnection()->setSlaveOkay($bool);
}
}
class EMongoException extends CException {}