MongoDB.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496
  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. if (is_bool($options)) {
  112. $options = ['includeSystemCollections' => $options];
  113. }
  114. $collections = $this->db->listCollections($options);
  115. $getCollectionName = function (CollectionInfo $collectionInfo) {
  116. return $collectionInfo->getName();
  117. };
  118. return array_map($getCollectionName, (array) $collections);
  119. }
  120. /**
  121. * @return MongoClient
  122. * @internal This method is not part of the ext-mongo API
  123. */
  124. public function getConnection()
  125. {
  126. return $this->connection;
  127. }
  128. /**
  129. * (PECL mongo &gt;= 0.9.0)<br/>
  130. * Fetches toolkit for dealing with files stored in this database
  131. * @link http://www.php.net/manual/en/mongodb.getgridfs.php
  132. * @param string $prefix [optional] The prefix for the files and chunks collections.
  133. * @return MongoGridFS Returns a new gridfs object for this database.
  134. */
  135. public function getGridFS($prefix = "fs")
  136. {
  137. return new \MongoGridFS($this, $prefix, $prefix);
  138. }
  139. /**
  140. * (PECL mongo &gt;= 0.9.0)<br/>
  141. * Gets this database's profiling level
  142. * @link http://www.php.net/manual/en/mongodb.getprofilinglevel.php
  143. * @return int Returns the profiling level.
  144. */
  145. public function getProfilingLevel()
  146. {
  147. return static::PROFILING_OFF;
  148. }
  149. /**
  150. * (PECL mongo &gt;= 0.9.0)<br/>
  151. * Sets this database's profiling level
  152. * @link http://www.php.net/manual/en/mongodb.setprofilinglevel.php
  153. * @param int $level Profiling level.
  154. * @return int Returns the previous profiling level.
  155. */
  156. public function setProfilingLevel($level)
  157. {
  158. return static::PROFILING_OFF;
  159. }
  160. /**
  161. * (PECL mongo &gt;= 0.9.0)<br/>
  162. * Drops this database
  163. * @link http://www.php.net/manual/en/mongodb.drop.php
  164. * @return array Returns the database response.
  165. */
  166. public function drop()
  167. {
  168. return $this->db->drop();
  169. }
  170. /**
  171. * Repairs and compacts this database
  172. * @link http://www.php.net/manual/en/mongodb.repair.php
  173. * @param bool $preserve_cloned_files [optional] <p>If cloned files should be kept if the repair fails.</p>
  174. * @param bool $backup_original_files [optional] <p>If original files should be backed up.</p>
  175. * @return array <p>Returns db response.</p>
  176. */
  177. public function repair($preserve_cloned_files = FALSE, $backup_original_files = FALSE)
  178. {
  179. return [];
  180. }
  181. /**
  182. * (PECL mongo &gt;= 0.9.0)<br/>
  183. * Gets a collection
  184. * @link http://www.php.net/manual/en/mongodb.selectcollection.php
  185. * @param string $name <b>The collection name.</b>
  186. * @throws Exception if the collection name is invalid.
  187. * @return MongoCollection <p>
  188. * Returns a new collection object.
  189. * </p>
  190. */
  191. public function selectCollection($name)
  192. {
  193. return new MongoCollection($this, $name);
  194. }
  195. /**
  196. * Creates a collection
  197. * @link http://www.php.net/manual/en/mongodb.createcollection.php
  198. * @param string $name The name of the collection.
  199. * @param array $options [optional] <p>
  200. * <p>
  201. * An array containing options for the collections. Each option is its own
  202. * element in the options array, with the option name listed below being
  203. * the key of the element. The supported options depend on the MongoDB
  204. * server version. At the moment, the following options are supported:
  205. * </p>
  206. * <p>
  207. * <b>capped</b>
  208. * <p>
  209. * If the collection should be a fixed size.
  210. * </p>
  211. * </p>
  212. * <p>
  213. * <b>size</b>
  214. * <p>
  215. * If the collection is fixed size, its size in bytes.</p></p>
  216. * <p><b>max</b>
  217. * <p>If the collection is fixed size, the maximum number of elements to store in the collection.</p></p>
  218. * <i>autoIndexId</i>
  219. *
  220. * <p>
  221. * If capped is <b>TRUE</b> you can specify <b>FALSE</b> to disable the
  222. * automatic index created on the <em>_id</em> field.
  223. * Before MongoDB 2.2, the default value for
  224. * <em>autoIndexId</em> was <b>FALSE</b>.
  225. * </p>
  226. * </p>
  227. * @return MongoCollection <p>Returns a collection object representing the new collection.</p>
  228. */
  229. public function createCollection($name, $options)
  230. {
  231. $this->db->createCollection($name, $options);
  232. return $this->selectCollection($name);
  233. }
  234. /**
  235. * (PECL mongo &gt;= 0.9.0)<br/>
  236. * @deprecated Use MongoCollection::drop() instead.
  237. * Drops a collection
  238. * @link http://www.php.net/manual/en/mongodb.dropcollection.php
  239. * @param MongoCollection|string $coll MongoCollection or name of collection to drop.
  240. * @return array Returns the database response.
  241. */
  242. public function dropCollection($coll)
  243. {
  244. return $this->db->dropCollection((string) $coll);
  245. }
  246. /**
  247. * (PECL mongo &gt;= 0.9.0)<br/>
  248. * Get a list of collections in this database
  249. * @link http://www.php.net/manual/en/mongodb.listcollections.php
  250. * @param bool $includeSystemCollections [optional] <p>Include system collections.</p>
  251. * @return array Returns a list of MongoCollections.
  252. */
  253. public function listCollections(array $options = [])
  254. {
  255. return array_map([$this, 'selectCollection'], $this->getCollectionNames($options));
  256. }
  257. /**
  258. * (PECL mongo &gt;= 0.9.0)<br/>
  259. * Creates a database reference
  260. * @link http://www.php.net/manual/en/mongodb.createdbref.php
  261. * @param string $collection The collection to which the database reference will point.
  262. * @param mixed $document_or_id <p>
  263. * If an array or object is given, its <em>_id</em> field will be
  264. * used as the reference ID. If a {@see MongoId} or scalar
  265. * is given, it will be used as the reference ID.
  266. * </p>
  267. * @return array <p>Returns a database reference array.</p>
  268. * <p>
  269. * If an array without an <em>_id</em> field was provided as the
  270. * <em>document_or_id</em> parameter, <b>NULL</b> will be returned.
  271. * </p>
  272. */
  273. public function createDBRef($collection, $document_or_id)
  274. {
  275. if (is_object($document_or_id)) {
  276. $id = isset($document_or_id->_id) ? $document_or_id->_id : null;
  277. // $id = $document_or_id->_id ?? null;
  278. } elseif (is_array($document_or_id)) {
  279. if (! isset($document_or_id['_id'])) {
  280. return null;
  281. }
  282. $id = $document_or_id['_id'];
  283. } else {
  284. $id = $document_or_id;
  285. }
  286. return [
  287. '$ref' => $collection,
  288. '$id' => $id,
  289. '$db' => $this->name,
  290. ];
  291. }
  292. /**
  293. * (PECL mongo &gt;= 0.9.0)<br/>
  294. * Fetches the document pointed to by a database reference
  295. * @link http://www.php.net/manual/en/mongodb.getdbref.php
  296. * @param array $ref A database reference.
  297. * @return array Returns the document pointed to by the reference.
  298. */
  299. public function getDBRef(array $ref)
  300. {
  301. $this->notImplemented();
  302. }
  303. /**
  304. * (PECL mongo &gt;= 0.9.3)<br/>
  305. * Runs JavaScript code on the database server.
  306. * @link http://www.php.net/manual/en/mongodb.execute.php
  307. * @param MongoCode|string $code Code to execute.
  308. * @param array $args [optional] Arguments to be passed to code.
  309. * @return array Returns the result of the evaluation.
  310. */
  311. public function execute($code, array $args = array())
  312. {
  313. $this->notImplemented();
  314. }
  315. /**
  316. * Execute a database command
  317. * @link http://www.php.net/manual/en/mongodb.command.php
  318. * @param array $data The query to send.
  319. * @param array() $options [optional] <p>
  320. * This parameter is an associative array of the form
  321. * <em>array("optionname" =&gt; &lt;boolean&gt;, ...)</em>. Currently
  322. * supported options are:
  323. * </p><ul>
  324. * <li><p><em>"timeout"</em></p><p>Deprecated alias for <em>"socketTimeoutMS"</em>.</p></li>
  325. * </ul>
  326. * @return array Returns database response.
  327. * Every database response is always maximum one document,
  328. * which means that the result of a database command can never exceed 16MB.
  329. * The resulting document's structure depends on the command,
  330. * but most results will have the ok field to indicate success or failure and results containing an array of each of the resulting documents.
  331. */
  332. public function command(array $data, $options, &$hash)
  333. {
  334. try {
  335. $cursor = new \MongoCommandCursor($this->connection, $this->name, $data);
  336. $cursor->setReadPreference($this->getReadPreference());
  337. return iterator_to_array($cursor)[0];
  338. } catch (\MongoDB\Driver\Exception\RuntimeException $e) {
  339. return [
  340. 'ok' => 0,
  341. 'errmsg' => $e->getMessage(),
  342. 'code' => $e->getCode(),
  343. ];
  344. }
  345. }
  346. /**
  347. * (PECL mongo &gt;= 0.9.5)<br/>
  348. * Check if there was an error on the most recent db operation performed
  349. * @link http://www.php.net/manual/en/mongodb.lasterror.php
  350. * @return array Returns the error, if there was one.
  351. */
  352. public function lastError()
  353. {
  354. $this->notImplemented();
  355. }
  356. /**
  357. * (PECL mongo &gt;= 0.9.5)<br/>
  358. * Checks for the last error thrown during a database operation
  359. * @link http://www.php.net/manual/en/mongodb.preverror.php
  360. * @return array Returns the error and the number of operations ago it occurred.
  361. */
  362. public function prevError()
  363. {
  364. $this->notImplemented();
  365. }
  366. /**
  367. * (PECL mongo &gt;= 0.9.5)<br/>
  368. * Clears any flagged errors on the database
  369. * @link http://www.php.net/manual/en/mongodb.reseterror.php
  370. * @return array Returns the database response.
  371. */
  372. public function resetError()
  373. {
  374. $this->notImplemented();
  375. }
  376. /**
  377. * (PECL mongo &gt;= 0.9.5)<br/>
  378. * Creates a database error
  379. * @link http://www.php.net/manual/en/mongodb.forceerror.php
  380. * @return boolean Returns the database response.
  381. */
  382. public function forceError()
  383. {
  384. $this->notImplemented();
  385. }
  386. /**
  387. * (PECL mongo &gt;= 1.0.1)<br/>
  388. * Log in to this database
  389. * @link http://www.php.net/manual/en/mongodb.authenticate.php
  390. * @param string $username The username.
  391. * @param string $password The password (in plaintext).
  392. * @return array <p>Returns database response. If the login was successful, it will return 1.</p>
  393. * <p>
  394. * <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>
  395. * </span>
  396. * </code></div>
  397. * </div>
  398. * </p>
  399. * <p> If something went wrong, it will return </p>
  400. * <p>
  401. * <div class="example-contents">
  402. * <div class="phpcode"><code><span style="color: #000000">
  403. * <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>
  404. * <p>("auth fails" could be another message, depending on database version and
  405. * what went wrong)</p>
  406. */
  407. public function authenticate($username, $password)
  408. {
  409. $this->notImplemented();
  410. }
  411. /**
  412. * {@inheritdoc}
  413. */
  414. public function setReadPreference($readPreference, $tags = null)
  415. {
  416. $result = $this->setReadPreferenceFromParameters($readPreference, $tags);
  417. $this->createDatabaseObject();
  418. return $result;
  419. }
  420. /**
  421. * {@inheritdoc}
  422. */
  423. public function setWriteConcern($wstring, $wtimeout = 0)
  424. {
  425. $result = $this->setWriteConcernFromParameters($wstring, $wtimeout);
  426. $this->createDatabaseObject();
  427. return $result;
  428. }
  429. protected function notImplemented()
  430. {
  431. throw new \Exception('Not implemented');
  432. }
  433. /**
  434. * @return \MongoDB\Database
  435. */
  436. private function createDatabaseObject()
  437. {
  438. $options = [
  439. 'readPreference' => $this->readPreference,
  440. 'writeConcern' => $this->writeConcern,
  441. ];
  442. if ($this->db === null) {
  443. $this->db = $this->connection->getClient()->selectDatabase($this->name, $options);
  444. } else {
  445. $this->db = $this->db->withOptions($options);
  446. }
  447. }
  448. }