MongoDB.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498
  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 Alcaeus\MongoDbAdapter\TypeConverter;
  17. use Alcaeus\MongoDbAdapter\ExceptionConverter;
  18. use MongoDB\Model\CollectionInfo;
  19. /**
  20. * Instances of this class are used to interact with a database.
  21. * @link http://www.php.net/manual/en/class.mongodb.php
  22. */
  23. class MongoDB
  24. {
  25. use Helper\ReadPreference;
  26. use Helper\SlaveOkay;
  27. use Helper\WriteConcern;
  28. const PROFILING_OFF = 0;
  29. const PROFILING_SLOW = 1;
  30. const PROFILING_ON = 2;
  31. /**
  32. * @var MongoClient
  33. */
  34. protected $connection;
  35. /**
  36. * @var \MongoDB\Database
  37. */
  38. protected $db;
  39. /**
  40. * @var string
  41. */
  42. protected $name;
  43. /**
  44. * Creates a new database
  45. *
  46. * 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()}.
  47. * @link http://www.php.net/manual/en/mongodb.construct.php
  48. * @param MongoClient $conn Database connection.
  49. * @param string $name Database name.
  50. * @throws Exception
  51. * @return MongoDB Returns the database.
  52. */
  53. public function __construct(MongoClient $conn, $name)
  54. {
  55. $this->connection = $conn;
  56. $this->name = $name;
  57. $this->setReadPreferenceFromArray($conn->getReadPreference());
  58. $this->setWriteConcernFromArray($conn->getWriteConcern());
  59. $this->createDatabaseObject();
  60. }
  61. /**
  62. * @return \MongoDB\Database
  63. * @internal This method is not part of the ext-mongo API
  64. */
  65. public function getDb()
  66. {
  67. return $this->db;
  68. }
  69. /**
  70. * The name of this database
  71. *
  72. * @link http://www.php.net/manual/en/mongodb.--tostring.php
  73. * @return string Returns this database's name.
  74. */
  75. public function __toString()
  76. {
  77. return $this->name;
  78. }
  79. /**
  80. * Gets a collection
  81. *
  82. * @link http://www.php.net/manual/en/mongodb.get.php
  83. * @param string $name The name of the collection.
  84. * @return MongoCollection
  85. */
  86. public function __get($name)
  87. {
  88. // Handle w and wtimeout properties that replicate data stored in $readPreference
  89. if ($name === 'w' || $name === 'wtimeout') {
  90. return $this->getWriteConcern()[$name];
  91. }
  92. return $this->selectCollection($name);
  93. }
  94. /**
  95. * @param string $name
  96. * @param mixed $value
  97. */
  98. public function __set($name, $value)
  99. {
  100. if ($name === 'w' || $name === 'wtimeout') {
  101. $this->setWriteConcernFromArray([$name => $value] + $this->getWriteConcern());
  102. $this->createDatabaseObject();
  103. }
  104. }
  105. /**
  106. * Returns information about collections in this database
  107. *
  108. * @link http://www.php.net/manual/en/mongodb.getcollectioninfo.php
  109. * @param array $options An array of options for listing the collections.
  110. * @return array
  111. */
  112. public function getCollectionInfo(array $options = [])
  113. {
  114. // The includeSystemCollections option is no longer supported
  115. if (isset($options['includeSystemCollections'])) {
  116. unset($options['includeSystemCollections']);
  117. }
  118. try {
  119. $collections = $this->db->listCollections($options);
  120. } catch (\MongoDB\Driver\Exception\Exception $e) {
  121. ExceptionConverter::toLegacy($e);
  122. }
  123. $getCollectionInfo = function (CollectionInfo $collectionInfo) {
  124. return [
  125. 'name' => $collectionInfo->getName(),
  126. 'options' => $collectionInfo->getOptions(),
  127. ];
  128. };
  129. return array_map($getCollectionInfo, iterator_to_array($collections));
  130. }
  131. /**
  132. * Get all collections from this database
  133. *
  134. * @link http://www.php.net/manual/en/mongodb.getcollectionnames.php
  135. * @param array $options An array of options for listing the collections.
  136. * @return array Returns the names of the all the collections in the database as an array
  137. */
  138. public function getCollectionNames(array $options = [])
  139. {
  140. // The includeSystemCollections option is no longer supported
  141. if (isset($options['includeSystemCollections'])) {
  142. unset($options['includeSystemCollections']);
  143. }
  144. try {
  145. $collections = $this->db->listCollections($options);
  146. } catch (\MongoDB\Driver\Exception\Exception $e) {
  147. ExceptionConverter::toLegacy($e);
  148. }
  149. $getCollectionName = function (CollectionInfo $collectionInfo) {
  150. return $collectionInfo->getName();
  151. };
  152. return array_map($getCollectionName, iterator_to_array($collections));
  153. }
  154. /**
  155. * @return MongoClient
  156. * @internal This method is not part of the ext-mongo API
  157. */
  158. public function getConnection()
  159. {
  160. return $this->connection;
  161. }
  162. /**
  163. * Fetches toolkit for dealing with files stored in this database
  164. *
  165. * @link http://www.php.net/manual/en/mongodb.getgridfs.php
  166. * @param string $prefix The prefix for the files and chunks collections.
  167. * @return MongoGridFS Returns a new gridfs object for this database.
  168. */
  169. public function getGridFS($prefix = "fs")
  170. {
  171. return new \MongoGridFS($this, $prefix);
  172. }
  173. /**
  174. * Gets this database's profiling level
  175. *
  176. * @link http://www.php.net/manual/en/mongodb.getprofilinglevel.php
  177. * @return int Returns the profiling level.
  178. */
  179. public function getProfilingLevel()
  180. {
  181. $result = $this->command(['profile' => -1]);
  182. return ($result['ok'] && isset($result['was'])) ? $result['was'] : 0;
  183. }
  184. /**
  185. * Sets this database's profiling level
  186. *
  187. * @link http://www.php.net/manual/en/mongodb.setprofilinglevel.php
  188. * @param int $level Profiling level.
  189. * @return int Returns the previous profiling level.
  190. */
  191. public function setProfilingLevel($level)
  192. {
  193. $result = $this->command(['profile' => $level]);
  194. return ($result['ok'] && isset($result['was'])) ? $result['was'] : 0;
  195. }
  196. /**
  197. * Drops this database
  198. *
  199. * @link http://www.php.net/manual/en/mongodb.drop.php
  200. * @return array Returns the database response.
  201. */
  202. public function drop()
  203. {
  204. return TypeConverter::toLegacy($this->db->drop());
  205. }
  206. /**
  207. * Repairs and compacts this database
  208. *
  209. * @link http://www.php.net/manual/en/mongodb.repair.php
  210. * @param bool $preserve_cloned_files [optional] <p>If cloned files should be kept if the repair fails.</p>
  211. * @param bool $backup_original_files [optional] <p>If original files should be backed up.</p>
  212. * @return array <p>Returns db response.</p>
  213. */
  214. public function repair($preserve_cloned_files = FALSE, $backup_original_files = FALSE)
  215. {
  216. $this->notImplemented();
  217. }
  218. /**
  219. * Gets a collection
  220. *
  221. * @link http://www.php.net/manual/en/mongodb.selectcollection.php
  222. * @param string $name <b>The collection name.</b>
  223. * @throws Exception if the collection name is invalid.
  224. * @return MongoCollection Returns a new collection object.
  225. */
  226. public function selectCollection($name)
  227. {
  228. return new MongoCollection($this, $name);
  229. }
  230. /**
  231. * Creates a collection
  232. *
  233. * @link http://www.php.net/manual/en/mongodb.createcollection.php
  234. * @param string $name The name of the collection.
  235. * @param array $options
  236. * @return MongoCollection Returns a collection object representing the new collection.
  237. */
  238. public function createCollection($name, $options)
  239. {
  240. try {
  241. $this->db->createCollection($name, $options);
  242. } catch (\MongoDB\Driver\Exception\Exception $e) {
  243. return false;
  244. }
  245. return $this->selectCollection($name);
  246. }
  247. /**
  248. * Drops a collection
  249. *
  250. * @link http://www.php.net/manual/en/mongodb.dropcollection.php
  251. * @param MongoCollection|string $coll MongoCollection or name of collection to drop.
  252. * @return array Returns the database response.
  253. *
  254. * @deprecated Use MongoCollection::drop() instead.
  255. */
  256. public function dropCollection($coll)
  257. {
  258. if ($coll instanceof MongoCollection) {
  259. $coll = $coll->getName();
  260. }
  261. return TypeConverter::toLegacy($this->db->dropCollection((string) $coll));
  262. }
  263. /**
  264. * Get a list of collections in this database
  265. *
  266. * @link http://www.php.net/manual/en/mongodb.listcollections.php
  267. * @param array $options
  268. * @return MongoCollection[] 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. * Creates a database reference
  276. *
  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
  280. * @return array Returns a database reference array.
  281. */
  282. public function createDBRef($collection, $document_or_id)
  283. {
  284. if ($document_or_id instanceof \MongoId) {
  285. $id = $document_or_id;
  286. } elseif (is_object($document_or_id)) {
  287. if (! isset($document_or_id->_id)) {
  288. return null;
  289. }
  290. $id = $document_or_id->_id;
  291. } elseif (is_array($document_or_id)) {
  292. if (! isset($document_or_id['_id'])) {
  293. return null;
  294. }
  295. $id = $document_or_id['_id'];
  296. } else {
  297. $id = $document_or_id;
  298. }
  299. return MongoDBRef::create($collection, $id, $this->name);
  300. }
  301. /**
  302. * Fetches the document pointed to by a database reference
  303. *
  304. * @link http://www.php.net/manual/en/mongodb.getdbref.php
  305. * @param array $ref A database reference.
  306. * @return array Returns the document pointed to by the reference.
  307. */
  308. public function getDBRef(array $ref)
  309. {
  310. return MongoDBRef::get($this, $ref);
  311. }
  312. /**
  313. * Runs JavaScript code on the database server.
  314. *
  315. * @link http://www.php.net/manual/en/mongodb.execute.php
  316. * @param MongoCode|string $code Code to execute.
  317. * @param array $args [optional] Arguments to be passed to code.
  318. * @return array Returns the result of the evaluation.
  319. */
  320. public function execute($code, array $args = [])
  321. {
  322. return $this->command(['eval' => $code, 'args' => $args]);
  323. }
  324. /**
  325. * Execute a database command
  326. *
  327. * @link http://www.php.net/manual/en/mongodb.command.php
  328. * @param array $data The query to send.
  329. * @param array $options
  330. * @return array Returns database response.
  331. */
  332. public function command(array $data, $options = [], &$hash = null)
  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\ExecutionTimeoutException $e) {
  339. throw new MongoCursorTimeoutException($e->getMessage(), $e->getCode(), $e);
  340. } catch (\MongoDB\Driver\Exception\RuntimeException $e) {
  341. return [
  342. 'ok' => 0,
  343. 'errmsg' => $e->getMessage(),
  344. 'code' => $e->getCode(),
  345. ];
  346. } catch (\MongoDB\Driver\Exception\Excepiton $e) {
  347. ExceptionConverter::toLegacy($e);
  348. }
  349. }
  350. /**
  351. * Check if there was an error on the most recent db operation performed
  352. *
  353. * @link http://www.php.net/manual/en/mongodb.lasterror.php
  354. * @return array Returns the error, if there was one.
  355. */
  356. public function lastError()
  357. {
  358. return $this->command(array('getLastError' => 1));
  359. }
  360. /**
  361. * Checks for the last error thrown during a database operation
  362. *
  363. * @link http://www.php.net/manual/en/mongodb.preverror.php
  364. * @return array Returns the error and the number of operations ago it occurred.
  365. */
  366. public function prevError()
  367. {
  368. return $this->command(array('getPrevError' => 1));
  369. }
  370. /**
  371. * Clears any flagged errors on the database
  372. *
  373. * @link http://www.php.net/manual/en/mongodb.reseterror.php
  374. * @return array Returns the database response.
  375. */
  376. public function resetError()
  377. {
  378. return $this->command(array('resetError' => 1));
  379. }
  380. /**
  381. * Creates a database error
  382. *
  383. * @link http://www.php.net/manual/en/mongodb.forceerror.php
  384. * @return boolean Returns the database response.
  385. */
  386. public function forceError()
  387. {
  388. return $this->command(array('forceerror' => 1));
  389. }
  390. /**
  391. * Log in to this database
  392. *
  393. * @link http://www.php.net/manual/en/mongodb.authenticate.php
  394. * @param string $username The username.
  395. * @param string $password The password (in plaintext).
  396. * @return array Returns database response. If the login was successful, it will return 1.
  397. *
  398. * @deprecated This method is not implemented, supply authentication credentials through the connection string instead.
  399. */
  400. public function authenticate($username, $password)
  401. {
  402. throw new \Exception('The MongoDB::authenticate method is not supported. Please supply authentication credentials through the connection string');
  403. }
  404. /**
  405. * {@inheritdoc}
  406. */
  407. public function setReadPreference($readPreference, $tags = null)
  408. {
  409. $result = $this->setReadPreferenceFromParameters($readPreference, $tags);
  410. $this->createDatabaseObject();
  411. return $result;
  412. }
  413. /**
  414. * {@inheritdoc}
  415. */
  416. public function setWriteConcern($wstring, $wtimeout = 0)
  417. {
  418. $result = $this->setWriteConcernFromParameters($wstring, $wtimeout);
  419. $this->createDatabaseObject();
  420. return $result;
  421. }
  422. protected function notImplemented()
  423. {
  424. throw new \Exception('Not implemented');
  425. }
  426. /**
  427. * @return \MongoDB\Database
  428. */
  429. private function createDatabaseObject()
  430. {
  431. $options = [
  432. 'readPreference' => $this->readPreference,
  433. 'writeConcern' => $this->writeConcern,
  434. ];
  435. if ($this->db === null) {
  436. $this->db = $this->connection->getClient()->selectDatabase($this->name, $options);
  437. } else {
  438. $this->db = $this->db->withOptions($options);
  439. }
  440. }
  441. }