MongoDB.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502
  1. <?php
  2. /*
  3. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  4. * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  5. * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  6. * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  7. * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  8. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  9. * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  10. * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  11. * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  12. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  13. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  14. */
  15. use Alcaeus\MongoDbAdapter\Helper;
  16. use MongoDB\Model\CollectionInfo;
  17. /**
  18. * Instances of this class are used to interact with a database.
  19. * @link http://www.php.net/manual/en/class.mongodb.php
  20. */
  21. class MongoDB
  22. {
  23. use Helper\ReadPreference;
  24. use Helper\SlaveOkay;
  25. use Helper\WriteConcern;
  26. const PROFILING_OFF = 0;
  27. const PROFILING_SLOW = 1;
  28. const PROFILING_ON = 2;
  29. /**
  30. * @var MongoClient
  31. */
  32. protected $connection;
  33. /**
  34. * @var \MongoDB\Database
  35. */
  36. protected $db;
  37. /**
  38. * @var string
  39. */
  40. protected $name;
  41. /**
  42. * Creates a new database
  43. *
  44. * This method is not meant to be called directly. The preferred way to create an instance of MongoDB is through {@see Mongo::__get()} or {@see Mongo::selectDB()}.
  45. * @link http://www.php.net/manual/en/mongodb.construct.php
  46. * @param MongoClient $conn Database connection.
  47. * @param string $name Database name.
  48. * @throws Exception
  49. * @return MongoDB Returns the database.
  50. */
  51. public function __construct(MongoClient $conn, $name)
  52. {
  53. $this->connection = $conn;
  54. $this->name = $name;
  55. $this->setReadPreferenceFromArray($conn->getReadPreference());
  56. $this->setWriteConcernFromArray($conn->getWriteConcern());
  57. $this->createDatabaseObject();
  58. }
  59. /**
  60. * @return \MongoDB\Database
  61. * @internal
  62. */
  63. public function getDb()
  64. {
  65. return $this->db;
  66. }
  67. /**
  68. * The name of this database
  69. * @link http://www.php.net/manual/en/mongodb.--tostring.php
  70. * @return string Returns this database's name.
  71. */
  72. public function __toString()
  73. {
  74. return $this->name;
  75. }
  76. /**
  77. * Gets a collection
  78. *
  79. * @link http://www.php.net/manual/en/mongodb.get.php
  80. * @param string $name The name of the collection.
  81. * @return MongoCollection
  82. */
  83. public function __get($name)
  84. {
  85. // Handle w and wtimeout properties that replicate data stored in $readPreference
  86. if ($name === 'w' || $name === 'wtimeout') {
  87. return $this->getWriteConcern()[$name];
  88. }
  89. return $this->selectCollection($name);
  90. }
  91. /**
  92. * @param string $name
  93. * @param mixed $value
  94. */
  95. public function __set($name, $value)
  96. {
  97. if ($name === 'w' || $name === 'wtimeout') {
  98. $this->setWriteConcernFromArray([$name => $value] + $this->getWriteConcern());
  99. $this->createDatabaseObject();
  100. }
  101. }
  102. /**
  103. * (PECL mongo &gt;= 1.3.0)<br/>
  104. * @link http://www.php.net/manual/en/mongodb.getcollectionnames.php
  105. * Get all collections from this database
  106. * @return array Returns the names of the all the collections in the database as an
  107. * {@link http://www.php.net/manual/en/language.types.array.php array}.
  108. */
  109. public function getCollectionNames(array $options = [])
  110. {
  111. // The includeSystemCollections option is no longer supported
  112. if (isset($options['includeSystemCollections'])) {
  113. unset($options['includeSystemCollections']);
  114. }
  115. $collections = $this->db->listCollections($options);
  116. $getCollectionName = function (CollectionInfo $collectionInfo) {
  117. return $collectionInfo->getName();
  118. };
  119. return array_map($getCollectionName, (array)$collections);
  120. }
  121. /**
  122. * @return MongoClient
  123. * @internal This method is not part of the ext-mongo API
  124. */
  125. public function getConnection()
  126. {
  127. return $this->connection;
  128. }
  129. /**
  130. * (PECL mongo &gt;= 0.9.0)<br/>
  131. * Fetches toolkit for dealing with files stored in this database
  132. * @link http://www.php.net/manual/en/mongodb.getgridfs.php
  133. * @param string $prefix [optional] The prefix for the files and chunks collections.
  134. * @return MongoGridFS Returns a new gridfs object for this database.
  135. */
  136. public function getGridFS($prefix = "fs")
  137. {
  138. return new \MongoGridFS($this, $prefix, $prefix);
  139. }
  140. /**
  141. * (PECL mongo &gt;= 0.9.0)<br/>
  142. * Gets this database's profiling level
  143. * @link http://www.php.net/manual/en/mongodb.getprofilinglevel.php
  144. * @return int Returns the profiling level.
  145. */
  146. public function getProfilingLevel()
  147. {
  148. $result = $this->command(['profile' => -1]);
  149. return ($result['ok'] && isset($result['was'])) ? $result['was'] : 0;
  150. }
  151. /**
  152. * (PECL mongo &gt;= 0.9.0)<br/>
  153. * Sets this database's profiling level
  154. * @link http://www.php.net/manual/en/mongodb.setprofilinglevel.php
  155. * @param int $level Profiling level.
  156. * @return int Returns the previous profiling level.
  157. */
  158. public function setProfilingLevel($level)
  159. {
  160. $result = $this->command(['profile' => $level]);
  161. return ($result['ok'] && isset($result['was'])) ? $result['was'] : 0;
  162. }
  163. /**
  164. * (PECL mongo &gt;= 0.9.0)<br/>
  165. * Drops this database
  166. * @link http://www.php.net/manual/en/mongodb.drop.php
  167. * @return array Returns the database response.
  168. */
  169. public function drop()
  170. {
  171. return $this->db->drop();
  172. }
  173. /**
  174. * Repairs and compacts this database
  175. * @link http://www.php.net/manual/en/mongodb.repair.php
  176. * @param bool $preserve_cloned_files [optional] <p>If cloned files should be kept if the repair fails.</p>
  177. * @param bool $backup_original_files [optional] <p>If original files should be backed up.</p>
  178. * @return array <p>Returns db response.</p>
  179. */
  180. public function repair($preserve_cloned_files = FALSE, $backup_original_files = FALSE)
  181. {
  182. return [];
  183. }
  184. /**
  185. * (PECL mongo &gt;= 0.9.0)<br/>
  186. * Gets a collection
  187. * @link http://www.php.net/manual/en/mongodb.selectcollection.php
  188. * @param string $name <b>The collection name.</b>
  189. * @throws Exception if the collection name is invalid.
  190. * @return MongoCollection <p>
  191. * Returns a new collection object.
  192. * </p>
  193. */
  194. public function selectCollection($name)
  195. {
  196. return new MongoCollection($this, $name);
  197. }
  198. /**
  199. * Creates a collection
  200. * @link http://www.php.net/manual/en/mongodb.createcollection.php
  201. * @param string $name The name of the collection.
  202. * @param array $options [optional] <p>
  203. * <p>
  204. * An array containing options for the collections. Each option is its own
  205. * element in the options array, with the option name listed below being
  206. * the key of the element. The supported options depend on the MongoDB
  207. * server version. At the moment, the following options are supported:
  208. * </p>
  209. * <p>
  210. * <b>capped</b>
  211. * <p>
  212. * If the collection should be a fixed size.
  213. * </p>
  214. * </p>
  215. * <p>
  216. * <b>size</b>
  217. * <p>
  218. * If the collection is fixed size, its size in bytes.</p></p>
  219. * <p><b>max</b>
  220. * <p>If the collection is fixed size, the maximum number of elements to store in the collection.</p></p>
  221. * <i>autoIndexId</i>
  222. *
  223. * <p>
  224. * If capped is <b>TRUE</b> you can specify <b>FALSE</b> to disable the
  225. * automatic index created on the <em>_id</em> field.
  226. * Before MongoDB 2.2, the default value for
  227. * <em>autoIndexId</em> was <b>FALSE</b>.
  228. * </p>
  229. * </p>
  230. * @return MongoCollection <p>Returns a collection object representing the new collection.</p>
  231. */
  232. public function createCollection($name, $options)
  233. {
  234. $this->db->createCollection($name, $options);
  235. return $this->selectCollection($name);
  236. }
  237. /**
  238. * (PECL mongo &gt;= 0.9.0)<br/>
  239. * @deprecated Use MongoCollection::drop() instead.
  240. * Drops a collection
  241. * @link http://www.php.net/manual/en/mongodb.dropcollection.php
  242. * @param MongoCollection|string $coll MongoCollection or name of collection to drop.
  243. * @return array Returns the database response.
  244. */
  245. public function dropCollection($coll)
  246. {
  247. return $this->db->dropCollection((string) $coll);
  248. }
  249. /**
  250. * (PECL mongo &gt;= 0.9.0)<br/>
  251. * Get a list of collections in this database
  252. * @link http://www.php.net/manual/en/mongodb.listcollections.php
  253. * @param bool $includeSystemCollections [optional] <p>Include system collections.</p>
  254. * @return array Returns a list of MongoCollections.
  255. */
  256. public function listCollections(array $options = [])
  257. {
  258. return array_map([$this, 'selectCollection'], $this->getCollectionNames($options));
  259. }
  260. /**
  261. * (PECL mongo &gt;= 0.9.0)<br/>
  262. * Creates a database reference
  263. * @link http://www.php.net/manual/en/mongodb.createdbref.php
  264. * @param string $collection The collection to which the database reference will point.
  265. * @param mixed $document_or_id <p>
  266. * If an array or object is given, its <em>_id</em> field will be
  267. * used as the reference ID. If a {@see MongoId} or scalar
  268. * is given, it will be used as the reference ID.
  269. * </p>
  270. * @return array <p>Returns a database reference array.</p>
  271. * <p>
  272. * If an array without an <em>_id</em> field was provided as the
  273. * <em>document_or_id</em> parameter, <b>NULL</b> will be returned.
  274. * </p>
  275. */
  276. public function createDBRef($collection, $document_or_id)
  277. {
  278. if ($document_or_id instanceof \MongoId) {
  279. $id = $document_or_id;
  280. } elseif (is_object($document_or_id)) {
  281. if (! isset($document_or_id->_id)) {
  282. return null;
  283. }
  284. $id = $document_or_id->_id;
  285. } elseif (is_array($document_or_id)) {
  286. if (! isset($document_or_id['_id'])) {
  287. return null;
  288. }
  289. $id = $document_or_id['_id'];
  290. } else {
  291. $id = $document_or_id;
  292. }
  293. return MongoDBRef::create($collection, $id, $this->name);
  294. }
  295. /**
  296. * (PECL mongo &gt;= 0.9.0)<br/>
  297. * Fetches the document pointed to by a database reference
  298. * @link http://www.php.net/manual/en/mongodb.getdbref.php
  299. * @param array $ref A database reference.
  300. * @return array Returns the document pointed to by the reference.
  301. */
  302. public function getDBRef(array $ref)
  303. {
  304. return MongoDBRef::get($this, $ref);
  305. }
  306. /**
  307. * Runs JavaScript code on the database server.
  308. *
  309. * @link http://www.php.net/manual/en/mongodb.execute.php
  310. * @param MongoCode|string $code Code to execute.
  311. * @param array $args [optional] Arguments to be passed to code.
  312. * @return array Returns the result of the evaluation.
  313. */
  314. public function execute($code, array $args = [])
  315. {
  316. return $this->command(['eval' => $code, 'args' => $args]);
  317. }
  318. /**
  319. * Execute a database command
  320. * @link http://www.php.net/manual/en/mongodb.command.php
  321. * @param array $data The query to send.
  322. * @param array() $options [optional] <p>
  323. * This parameter is an associative array of the form
  324. * <em>array("optionname" =&gt; &lt;boolean&gt;, ...)</em>. Currently
  325. * supported options are:
  326. * </p><ul>
  327. * <li><p><em>"timeout"</em></p><p>Deprecated alias for <em>"socketTimeoutMS"</em>.</p></li>
  328. * </ul>
  329. * @return array Returns database response.
  330. * Every database response is always maximum one document,
  331. * which means that the result of a database command can never exceed 16MB.
  332. * The resulting document's structure depends on the command,
  333. * but most results will have the ok field to indicate success or failure and results containing an array of each of the resulting documents.
  334. */
  335. public function command(array $data, $options = [], &$hash = null)
  336. {
  337. try {
  338. $cursor = new \MongoCommandCursor($this->connection, $this->name, $data);
  339. $cursor->setReadPreference($this->getReadPreference());
  340. return iterator_to_array($cursor)[0];
  341. } catch (\MongoDB\Driver\Exception\RuntimeException $e) {
  342. return [
  343. 'ok' => 0,
  344. 'errmsg' => $e->getMessage(),
  345. 'code' => $e->getCode(),
  346. ];
  347. }
  348. }
  349. /**
  350. * Check if there was an error on the most recent db operation performed
  351. *
  352. * @link http://www.php.net/manual/en/mongodb.lasterror.php
  353. * @return array Returns the error, if there was one.
  354. */
  355. public function lastError()
  356. {
  357. return $this->command(array('getLastError' => 1));
  358. }
  359. /**
  360. * Checks for the last error thrown during a database operation
  361. *
  362. * @link http://www.php.net/manual/en/mongodb.preverror.php
  363. * @return array Returns the error and the number of operations ago it occurred.
  364. */
  365. public function prevError()
  366. {
  367. return $this->command(array('getPrevError' => 1));
  368. }
  369. /**
  370. * Clears any flagged errors on the database
  371. *
  372. * @link http://www.php.net/manual/en/mongodb.reseterror.php
  373. * @return array Returns the database response.
  374. */
  375. public function resetError()
  376. {
  377. return $this->command(array('resetError' => 1));
  378. }
  379. /**
  380. * Creates a database error
  381. *
  382. * @link http://www.php.net/manual/en/mongodb.forceerror.php
  383. * @return boolean Returns the database response.
  384. */
  385. public function forceError()
  386. {
  387. return $this->command(array('forceerror' => 1));
  388. }
  389. /**
  390. * (PECL mongo &gt;= 1.0.1)<br/>
  391. * Log in to this database
  392. * @link http://www.php.net/manual/en/mongodb.authenticate.php
  393. * @param string $username The username.
  394. * @param string $password The password (in plaintext).
  395. * @return array <p>Returns database response. If the login was successful, it will return 1.</p>
  396. * <p>
  397. * <span style="color: #0000BB">&lt;?php<br></span><span style="color: #007700">array(</span><span style="color: #DD0000">"ok"&nbsp;</span><span style="color: #007700">=&gt;&nbsp;</span><span style="color: #0000BB">1</span><span style="color: #007700">);<br></span><span style="color: #0000BB">?&gt;</span>
  398. * </span>
  399. * </code></div>
  400. * </div>
  401. * </p>
  402. * <p> If something went wrong, it will return </p>
  403. * <p>
  404. * <div class="example-contents">
  405. * <div class="phpcode"><code><span style="color: #000000">
  406. * <span style="color: #0000BB">&lt;?php<br></span><span style="color: #007700">array(</span><span style="color: #DD0000">"ok"&nbsp;</span><span style="color: #007700">=&gt;&nbsp;</span><span style="color: #0000BB">0</span><span style="color: #007700">,&nbsp;</span><span style="color: #DD0000">"errmsg"&nbsp;</span><span style="color: #007700">=&gt;&nbsp;</span><span style="color: #DD0000">"auth&nbsp;fails"</span><span style="color: #007700">);<br></span><span style="color: #0000BB">?&gt;</span></p>
  407. * <p>("auth fails" could be another message, depending on database version and
  408. * what went wrong)</p>
  409. */
  410. public function authenticate($username, $password)
  411. {
  412. $this->notImplemented();
  413. }
  414. /**
  415. * {@inheritdoc}
  416. */
  417. public function setReadPreference($readPreference, $tags = null)
  418. {
  419. $result = $this->setReadPreferenceFromParameters($readPreference, $tags);
  420. $this->createDatabaseObject();
  421. return $result;
  422. }
  423. /**
  424. * {@inheritdoc}
  425. */
  426. public function setWriteConcern($wstring, $wtimeout = 0)
  427. {
  428. $result = $this->setWriteConcernFromParameters($wstring, $wtimeout);
  429. $this->createDatabaseObject();
  430. return $result;
  431. }
  432. protected function notImplemented()
  433. {
  434. throw new \Exception('Not implemented');
  435. }
  436. /**
  437. * @return \MongoDB\Database
  438. */
  439. private function createDatabaseObject()
  440. {
  441. $options = [
  442. 'readPreference' => $this->readPreference,
  443. 'writeConcern' => $this->writeConcern,
  444. ];
  445. if ($this->db === null) {
  446. $this->db = $this->connection->getClient()->selectDatabase($this->name, $options);
  447. } else {
  448. $this->db = $this->db->withOptions($options);
  449. }
  450. }
  451. }