MongoDB.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450
  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 This method is not part of the ext-mongo API
  62. */
  63. public function getDb()
  64. {
  65. return $this->db;
  66. }
  67. /**
  68. * The name of this database
  69. *
  70. * @link http://www.php.net/manual/en/mongodb.--tostring.php
  71. * @return string Returns this database's name.
  72. */
  73. public function __toString()
  74. {
  75. return $this->name;
  76. }
  77. /**
  78. * Gets a collection
  79. *
  80. * @link http://www.php.net/manual/en/mongodb.get.php
  81. * @param string $name The name of the collection.
  82. * @return MongoCollection
  83. */
  84. public function __get($name)
  85. {
  86. // Handle w and wtimeout properties that replicate data stored in $readPreference
  87. if ($name === 'w' || $name === 'wtimeout') {
  88. return $this->getWriteConcern()[$name];
  89. }
  90. return $this->selectCollection($name);
  91. }
  92. /**
  93. * @param string $name
  94. * @param mixed $value
  95. */
  96. public function __set($name, $value)
  97. {
  98. if ($name === 'w' || $name === 'wtimeout') {
  99. $this->setWriteConcernFromArray([$name => $value] + $this->getWriteConcern());
  100. $this->createDatabaseObject();
  101. }
  102. }
  103. /**
  104. * Get all collections from this database
  105. *
  106. * @link http://www.php.net/manual/en/mongodb.getcollectionnames.php
  107. * @return array Returns the names of the all the collections in the database as an 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. * Fetches toolkit for dealing with files stored in this database
  131. *
  132. * @link http://www.php.net/manual/en/mongodb.getgridfs.php
  133. * @param string $prefix 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. * Gets this database's profiling level
  142. *
  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. * Sets this database's profiling level
  153. *
  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. * Drops this database
  165. *
  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. *
  176. * @link http://www.php.net/manual/en/mongodb.repair.php
  177. * @param bool $preserve_cloned_files [optional] <p>If cloned files should be kept if the repair fails.</p>
  178. * @param bool $backup_original_files [optional] <p>If original files should be backed up.</p>
  179. * @return array <p>Returns db response.</p>
  180. */
  181. public function repair($preserve_cloned_files = FALSE, $backup_original_files = FALSE)
  182. {
  183. return [];
  184. }
  185. /**
  186. * Gets a collection
  187. *
  188. * @link http://www.php.net/manual/en/mongodb.selectcollection.php
  189. * @param string $name <b>The collection name.</b>
  190. * @throws Exception if the collection name is invalid.
  191. * @return MongoCollection Returns a new collection object.
  192. */
  193. public function selectCollection($name)
  194. {
  195. return new MongoCollection($this, $name);
  196. }
  197. /**
  198. * Creates a collection
  199. *
  200. * @link http://www.php.net/manual/en/mongodb.createcollection.php
  201. * @param string $name The name of the collection.
  202. * @param array $options
  203. * @return MongoCollection Returns a collection object representing the new collection.
  204. */
  205. public function createCollection($name, $options)
  206. {
  207. $this->db->createCollection($name, $options);
  208. return $this->selectCollection($name);
  209. }
  210. /**
  211. * Drops a collection
  212. *
  213. * @link http://www.php.net/manual/en/mongodb.dropcollection.php
  214. * @param MongoCollection|string $coll MongoCollection or name of collection to drop.
  215. * @return array Returns the database response.
  216. *
  217. * @deprecated Use MongoCollection::drop() instead.
  218. */
  219. public function dropCollection($coll)
  220. {
  221. if ($coll instanceof MongoCollection) {
  222. $coll = $coll->getName();
  223. }
  224. return $this->db->dropCollection((string) $coll);
  225. }
  226. /**
  227. * Get a list of collections in this database
  228. *
  229. * @link http://www.php.net/manual/en/mongodb.listcollections.php
  230. * @param array $options
  231. * @return array Returns a list of MongoCollections.
  232. */
  233. public function listCollections(array $options = [])
  234. {
  235. return array_map([$this, 'selectCollection'], $this->getCollectionNames($options));
  236. }
  237. /**
  238. * Creates a database reference
  239. *
  240. * @link http://www.php.net/manual/en/mongodb.createdbref.php
  241. * @param string $collection The collection to which the database reference will point.
  242. * @param mixed $document_or_id
  243. * @return array Returns a database reference array.
  244. */
  245. public function createDBRef($collection, $document_or_id)
  246. {
  247. if ($document_or_id instanceof \MongoId) {
  248. $id = $document_or_id;
  249. } elseif (is_object($document_or_id)) {
  250. if (! isset($document_or_id->_id)) {
  251. return null;
  252. }
  253. $id = $document_or_id->_id;
  254. } elseif (is_array($document_or_id)) {
  255. if (! isset($document_or_id['_id'])) {
  256. return null;
  257. }
  258. $id = $document_or_id['_id'];
  259. } else {
  260. $id = $document_or_id;
  261. }
  262. return MongoDBRef::create($collection, $id, $this->name);
  263. }
  264. /**
  265. * Fetches the document pointed to by a database reference
  266. *
  267. * @link http://www.php.net/manual/en/mongodb.getdbref.php
  268. * @param array $ref A database reference.
  269. * @return array Returns the document pointed to by the reference.
  270. */
  271. public function getDBRef(array $ref)
  272. {
  273. return MongoDBRef::get($this, $ref);
  274. }
  275. /**
  276. * Runs JavaScript code on the database server.
  277. *
  278. * @link http://www.php.net/manual/en/mongodb.execute.php
  279. * @param MongoCode|string $code Code to execute.
  280. * @param array $args [optional] Arguments to be passed to code.
  281. * @return array Returns the result of the evaluation.
  282. */
  283. public function execute($code, array $args = [])
  284. {
  285. return $this->command(['eval' => $code, 'args' => $args]);
  286. }
  287. /**
  288. * Execute a database command
  289. *
  290. * @link http://www.php.net/manual/en/mongodb.command.php
  291. * @param array $data The query to send.
  292. * @param array $options
  293. * @return array Returns database response.
  294. */
  295. public function command(array $data, $options = [], &$hash = null)
  296. {
  297. try {
  298. $cursor = new \MongoCommandCursor($this->connection, $this->name, $data);
  299. $cursor->setReadPreference($this->getReadPreference());
  300. return iterator_to_array($cursor)[0];
  301. } catch (\MongoDB\Driver\Exception\RuntimeException $e) {
  302. return [
  303. 'ok' => 0,
  304. 'errmsg' => $e->getMessage(),
  305. 'code' => $e->getCode(),
  306. ];
  307. }
  308. }
  309. /**
  310. * Check if there was an error on the most recent db operation performed
  311. *
  312. * @link http://www.php.net/manual/en/mongodb.lasterror.php
  313. * @return array Returns the error, if there was one.
  314. */
  315. public function lastError()
  316. {
  317. return $this->command(array('getLastError' => 1));
  318. }
  319. /**
  320. * Checks for the last error thrown during a database operation
  321. *
  322. * @link http://www.php.net/manual/en/mongodb.preverror.php
  323. * @return array Returns the error and the number of operations ago it occurred.
  324. */
  325. public function prevError()
  326. {
  327. return $this->command(array('getPrevError' => 1));
  328. }
  329. /**
  330. * Clears any flagged errors on the database
  331. *
  332. * @link http://www.php.net/manual/en/mongodb.reseterror.php
  333. * @return array Returns the database response.
  334. */
  335. public function resetError()
  336. {
  337. return $this->command(array('resetError' => 1));
  338. }
  339. /**
  340. * Creates a database error
  341. *
  342. * @link http://www.php.net/manual/en/mongodb.forceerror.php
  343. * @return boolean Returns the database response.
  344. */
  345. public function forceError()
  346. {
  347. return $this->command(array('forceerror' => 1));
  348. }
  349. /**
  350. * Log in to this database
  351. *
  352. * @link http://www.php.net/manual/en/mongodb.authenticate.php
  353. * @param string $username The username.
  354. * @param string $password The password (in plaintext).
  355. * @return array Returns database response. If the login was successful, it will return 1.
  356. */
  357. public function authenticate($username, $password)
  358. {
  359. $this->notImplemented();
  360. }
  361. /**
  362. * {@inheritdoc}
  363. */
  364. public function setReadPreference($readPreference, $tags = null)
  365. {
  366. $result = $this->setReadPreferenceFromParameters($readPreference, $tags);
  367. $this->createDatabaseObject();
  368. return $result;
  369. }
  370. /**
  371. * {@inheritdoc}
  372. */
  373. public function setWriteConcern($wstring, $wtimeout = 0)
  374. {
  375. $result = $this->setWriteConcernFromParameters($wstring, $wtimeout);
  376. $this->createDatabaseObject();
  377. return $result;
  378. }
  379. protected function notImplemented()
  380. {
  381. throw new \Exception('Not implemented');
  382. }
  383. /**
  384. * @return \MongoDB\Database
  385. */
  386. private function createDatabaseObject()
  387. {
  388. $options = [
  389. 'readPreference' => $this->readPreference,
  390. 'writeConcern' => $this->writeConcern,
  391. ];
  392. if ($this->db === null) {
  393. $this->db = $this->connection->getClient()->selectDatabase($this->name, $options);
  394. } else {
  395. $this->db = $this->db->withOptions($options);
  396. }
  397. }
  398. }