MongoDB.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512
  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\WriteConcern;
  25. const PROFILING_OFF = 0;
  26. const PROFILING_SLOW = 1;
  27. const PROFILING_ON = 2;
  28. /**
  29. * @var \MongoDB\Database
  30. */
  31. protected $db;
  32. /**
  33. * Creates a new database
  34. *
  35. * 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()}.
  36. * @link http://www.php.net/manual/en/mongodb.construct.php
  37. * @param MongoClient $conn Database connection.
  38. * @param string $name Database name.
  39. * @throws Exception
  40. * @return MongoDB Returns the database.
  41. */
  42. public function __construct($conn, $name)
  43. {
  44. $this->connection = $conn;
  45. $this->name = $name;
  46. $this->setReadPreferenceFromArray($conn->getReadPreference());
  47. $this->setWriteConcernFromArray($conn->getWriteConcern());
  48. $this->createDatabaseObject();
  49. }
  50. /**
  51. * @return \MongoDB\Database
  52. * @internal
  53. */
  54. public function getDb()
  55. {
  56. return $this->db;
  57. }
  58. /**
  59. * The name of this database
  60. * @link http://www.php.net/manual/en/mongodb.--tostring.php
  61. * @return string Returns this database's name.
  62. */
  63. public function __toString()
  64. {
  65. return $this->name;
  66. }
  67. /**
  68. * Gets a collection
  69. *
  70. * @link http://www.php.net/manual/en/mongodb.get.php
  71. * @param string $name The name of the collection.
  72. * @return MongoCollection
  73. */
  74. public function __get($name)
  75. {
  76. // Handle w and wtimeout properties that replicate data stored in $readPreference
  77. if ($name === 'w' || $name === 'wtimeout') {
  78. return $this->getWriteConcern()[$name];
  79. }
  80. return $this->selectCollection($name);
  81. }
  82. /**
  83. * @param string $name
  84. * @param mixed $value
  85. */
  86. public function __set($name, $value)
  87. {
  88. if ($name === 'w' || $name === 'wtimeout') {
  89. $this->setWriteConcernFromArray([$name => $value] + $this->getWriteConcern());
  90. $this->createDatabaseObject();
  91. } else {
  92. $this->$name = $value;
  93. }
  94. }
  95. /**
  96. * (PECL mongo &gt;= 1.3.0)<br/>
  97. * @link http://www.php.net/manual/en/mongodb.getcollectionnames.php
  98. * Get all collections from this database
  99. * @return array Returns the names of the all the collections in the database as an
  100. * {@link http://www.php.net/manual/en/language.types.array.php array}.
  101. */
  102. public function getCollectionNames(array $options = [])
  103. {
  104. if (is_bool($options)) {
  105. $options = ['includeSystemCollections' => $options];
  106. }
  107. $collections = $this->db->listCollections($options);
  108. $getCollectionName = function (CollectionInfo $collectionInfo) {
  109. return $collectionInfo->getName();
  110. };
  111. return array_map($getCollectionName, (array) $collections);
  112. }
  113. /**
  114. * @return MongoClient
  115. * @internal This method is not part of the ext-mongo API
  116. */
  117. public function getConnection()
  118. {
  119. return $this->connection;
  120. }
  121. /**
  122. * (PECL mongo &gt;= 0.9.0)<br/>
  123. * Fetches toolkit for dealing with files stored in this database
  124. * @link http://www.php.net/manual/en/mongodb.getgridfs.php
  125. * @param string $prefix [optional] The prefix for the files and chunks collections.
  126. * @return MongoGridFS Returns a new gridfs object for this database.
  127. */
  128. public function getGridFS($prefix = "fs")
  129. {
  130. return new \MongoGridFS($this, $prefix, $prefix);
  131. }
  132. /**
  133. * (PECL mongo &gt;= 0.9.0)<br/>
  134. * Gets this database's profiling level
  135. * @link http://www.php.net/manual/en/mongodb.getprofilinglevel.php
  136. * @return int Returns the profiling level.
  137. */
  138. public function getProfilingLevel()
  139. {
  140. return static::PROFILING_OFF;
  141. }
  142. /**
  143. * (PECL mongo &gt;= 1.1.0)<br/>
  144. * Get slaveOkay setting for this database
  145. * @link http://www.php.net/manual/en/mongodb.getslaveokay.php
  146. * @return bool Returns the value of slaveOkay for this instance.
  147. */
  148. public function getSlaveOkay()
  149. {
  150. return false;
  151. }
  152. /**
  153. * (PECL mongo &gt;= 0.9.0)<br/>
  154. * Sets this database's profiling level
  155. * @link http://www.php.net/manual/en/mongodb.setprofilinglevel.php
  156. * @param int $level Profiling level.
  157. * @return int Returns the previous profiling level.
  158. */
  159. public function setProfilingLevel($level)
  160. {
  161. return static::PROFILING_OFF;
  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. * (PECL mongo &gt;= 1.1.0)<br/>
  200. * Change slaveOkay setting for this database
  201. * @link http://php.net/manual/en/mongodb.setslaveokay.php
  202. * @param bool $ok [optional] <p>
  203. * If reads should be sent to secondary members of a replica set for all
  204. * possible queries using this {@link http://www.php.net/manual/en/class.mongodb.php MongoDB} instance.
  205. * </p>
  206. * @return bool Returns the former value of slaveOkay for this instance.
  207. */
  208. public function setSlaveOkay ($ok = true)
  209. {
  210. return false;
  211. }
  212. /**
  213. * Creates a collection
  214. * @link http://www.php.net/manual/en/mongodb.createcollection.php
  215. * @param string $name The name of the collection.
  216. * @param array $options [optional] <p>
  217. * <p>
  218. * An array containing options for the collections. Each option is its own
  219. * element in the options array, with the option name listed below being
  220. * the key of the element. The supported options depend on the MongoDB
  221. * server version. At the moment, the following options are supported:
  222. * </p>
  223. * <p>
  224. * <b>capped</b>
  225. * <p>
  226. * If the collection should be a fixed size.
  227. * </p>
  228. * </p>
  229. * <p>
  230. * <b>size</b>
  231. * <p>
  232. * If the collection is fixed size, its size in bytes.</p></p>
  233. * <p><b>max</b>
  234. * <p>If the collection is fixed size, the maximum number of elements to store in the collection.</p></p>
  235. * <i>autoIndexId</i>
  236. *
  237. * <p>
  238. * If capped is <b>TRUE</b> you can specify <b>FALSE</b> to disable the
  239. * automatic index created on the <em>_id</em> field.
  240. * Before MongoDB 2.2, the default value for
  241. * <em>autoIndexId</em> was <b>FALSE</b>.
  242. * </p>
  243. * </p>
  244. * @return MongoCollection <p>Returns a collection object representing the new collection.</p>
  245. */
  246. public function createCollection($name, $options)
  247. {
  248. $this->db->createCollection($name, $options);
  249. return $this->selectCollection($name);
  250. }
  251. /**
  252. * (PECL mongo &gt;= 0.9.0)<br/>
  253. * @deprecated Use MongoCollection::drop() instead.
  254. * Drops a collection
  255. * @link http://www.php.net/manual/en/mongodb.dropcollection.php
  256. * @param MongoCollection|string $coll MongoCollection or name of collection to drop.
  257. * @return array Returns the database response.
  258. */
  259. public function dropCollection($coll)
  260. {
  261. return $this->db->dropCollection((string) $coll);
  262. }
  263. /**
  264. * (PECL mongo &gt;= 0.9.0)<br/>
  265. * Get a list of collections in this database
  266. * @link http://www.php.net/manual/en/mongodb.listcollections.php
  267. * @param bool $includeSystemCollections [optional] <p>Include system collections.</p>
  268. * @return array Returns a list of MongoCollections.
  269. */
  270. public function listCollections(array $options = [])
  271. {
  272. return array_map([$this, 'selectCollection'], $this->getCollectionNames($options));
  273. }
  274. /**
  275. * (PECL mongo &gt;= 0.9.0)<br/>
  276. * Creates a database reference
  277. * @link http://www.php.net/manual/en/mongodb.createdbref.php
  278. * @param string $collection The collection to which the database reference will point.
  279. * @param mixed $document_or_id <p>
  280. * If an array or object is given, its <em>_id</em> field will be
  281. * used as the reference ID. If a {@see MongoId} or scalar
  282. * is given, it will be used as the reference ID.
  283. * </p>
  284. * @return array <p>Returns a database reference array.</p>
  285. * <p>
  286. * If an array without an <em>_id</em> field was provided as the
  287. * <em>document_or_id</em> parameter, <b>NULL</b> will be returned.
  288. * </p>
  289. */
  290. public function createDBRef($collection, $document_or_id)
  291. {
  292. if (is_object($document_or_id)) {
  293. $id = isset($document_or_id->_id) ? $document_or_id->_id : null;
  294. // $id = $document_or_id->_id ?? null;
  295. } elseif (is_array($document_or_id)) {
  296. if (! isset($document_or_id['_id'])) {
  297. return null;
  298. }
  299. $id = $document_or_id['_id'];
  300. } else {
  301. $id = $document_or_id;
  302. }
  303. return [
  304. '$ref' => $collection,
  305. '$id' => $id,
  306. '$db' => $this->name,
  307. ];
  308. }
  309. /**
  310. * (PECL mongo &gt;= 0.9.0)<br/>
  311. * Fetches the document pointed to by a database reference
  312. * @link http://www.php.net/manual/en/mongodb.getdbref.php
  313. * @param array $ref A database reference.
  314. * @return array Returns the document pointed to by the reference.
  315. */
  316. public function getDBRef(array $ref)
  317. {
  318. $this->notImplemented();
  319. }
  320. /**
  321. * (PECL mongo &gt;= 0.9.3)<br/>
  322. * Runs JavaScript code on the database server.
  323. * @link http://www.php.net/manual/en/mongodb.execute.php
  324. * @param MongoCode|string $code Code to execute.
  325. * @param array $args [optional] Arguments to be passed to code.
  326. * @return array Returns the result of the evaluation.
  327. */
  328. public function execute($code, array $args = array())
  329. {
  330. $this->notImplemented();
  331. }
  332. /**
  333. * Execute a database command
  334. * @link http://www.php.net/manual/en/mongodb.command.php
  335. * @param array $data The query to send.
  336. * @param array() $options [optional] <p>
  337. * This parameter is an associative array of the form
  338. * <em>array("optionname" =&gt; &lt;boolean&gt;, ...)</em>. Currently
  339. * supported options are:
  340. * </p><ul>
  341. * <li><p><em>"timeout"</em></p><p>Deprecated alias for <em>"socketTimeoutMS"</em>.</p></li>
  342. * </ul>
  343. * @return array Returns database response.
  344. * Every database response is always maximum one document,
  345. * which means that the result of a database command can never exceed 16MB.
  346. * The resulting document's structure depends on the command,
  347. * but most results will have the ok field to indicate success or failure and results containing an array of each of the resulting documents.
  348. */
  349. public function command(array $data, $options, &$hash)
  350. {
  351. try {
  352. $cursor = new \MongoCommandCursor($this->connection, $this->name, $data);
  353. return iterator_to_array($cursor)[0];
  354. } catch (\MongoDB\Driver\Exception\RuntimeException $e) {
  355. return [
  356. 'ok' => 0,
  357. 'errmsg' => $e->getMessage(),
  358. 'code' => $e->getCode(),
  359. ];
  360. }
  361. }
  362. /**
  363. * (PECL mongo &gt;= 0.9.5)<br/>
  364. * Check if there was an error on the most recent db operation performed
  365. * @link http://www.php.net/manual/en/mongodb.lasterror.php
  366. * @return array Returns the error, if there was one.
  367. */
  368. public function lastError()
  369. {
  370. $this->notImplemented();
  371. }
  372. /**
  373. * (PECL mongo &gt;= 0.9.5)<br/>
  374. * Checks for the last error thrown during a database operation
  375. * @link http://www.php.net/manual/en/mongodb.preverror.php
  376. * @return array Returns the error and the number of operations ago it occurred.
  377. */
  378. public function prevError()
  379. {
  380. $this->notImplemented();
  381. }
  382. /**
  383. * (PECL mongo &gt;= 0.9.5)<br/>
  384. * Clears any flagged errors on the database
  385. * @link http://www.php.net/manual/en/mongodb.reseterror.php
  386. * @return array Returns the database response.
  387. */
  388. public function resetError()
  389. {
  390. $this->notImplemented();
  391. }
  392. /**
  393. * (PECL mongo &gt;= 0.9.5)<br/>
  394. * Creates a database error
  395. * @link http://www.php.net/manual/en/mongodb.forceerror.php
  396. * @return boolean Returns the database response.
  397. */
  398. public function forceError()
  399. {
  400. $this->notImplemented();
  401. }
  402. /**
  403. * (PECL mongo &gt;= 1.0.1)<br/>
  404. * Log in to this database
  405. * @link http://www.php.net/manual/en/mongodb.authenticate.php
  406. * @param string $username The username.
  407. * @param string $password The password (in plaintext).
  408. * @return array <p>Returns database response. If the login was successful, it will return 1.</p>
  409. * <p>
  410. * <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>
  411. * </span>
  412. * </code></div>
  413. * </div>
  414. * </p>
  415. * <p> If something went wrong, it will return </p>
  416. * <p>
  417. * <div class="example-contents">
  418. * <div class="phpcode"><code><span style="color: #000000">
  419. * <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>
  420. * <p>("auth fails" could be another message, depending on database version and
  421. * what went wrong)</p>
  422. */
  423. public function authenticate($username, $password)
  424. {
  425. $this->notImplemented();
  426. }
  427. /**
  428. * {@inheritdoc}
  429. */
  430. public function setReadPreference($readPreference, $tags = null)
  431. {
  432. $result = $this->setReadPreferenceFromParameters($readPreference, $tags);
  433. $this->createDatabaseObject();
  434. return $result;
  435. }
  436. /**
  437. * {@inheritdoc}
  438. */
  439. public function setWriteConcern($wstring, $wtimeout = 0)
  440. {
  441. $result = $this->setWriteConcernFromParameters($wstring, $wtimeout);
  442. $this->createDatabaseObject();
  443. return $result;
  444. }
  445. protected function notImplemented()
  446. {
  447. throw new \Exception('Not implemented');
  448. }
  449. /**
  450. * @return \MongoDB\Database
  451. */
  452. private function createDatabaseObject()
  453. {
  454. $options = [
  455. 'readPreference' => $this->readPreference,
  456. 'writeConcern' => $this->writeConcern,
  457. ];
  458. if ($this->db === null) {
  459. $this->db = $this->connection->getClient()->selectDatabase($this->name, $options);
  460. } else {
  461. $this->db = $this->db->withOptions($options);
  462. }
  463. }
  464. }