MongoClient.php 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352
  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. if (class_exists('MongoClient', false)) {
  16. return;
  17. }
  18. use Alcaeus\MongoDbAdapter\Helper;
  19. use Alcaeus\MongoDbAdapter\ExceptionConverter;
  20. use MongoDB\Client;
  21. /**
  22. * A connection between PHP and MongoDB. This class is used to create and manage connections
  23. * See MongoClient::__construct() and the section on connecting for more information about creating connections.
  24. * @link http://www.php.net/manual/en/class.mongoclient.php
  25. */
  26. class MongoClient
  27. {
  28. use Helper\ReadPreference;
  29. use Helper\WriteConcern;
  30. const VERSION = '1.6.12';
  31. const DEFAULT_HOST = "localhost" ;
  32. const DEFAULT_PORT = 27017 ;
  33. const RP_PRIMARY = "primary" ;
  34. const RP_PRIMARY_PREFERRED = "primaryPreferred" ;
  35. const RP_SECONDARY = "secondary" ;
  36. const RP_SECONDARY_PREFERRED = "secondaryPreferred" ;
  37. const RP_NEAREST = "nearest" ;
  38. /**
  39. * @var bool
  40. * @deprecated This will not properly work as the underlying driver connects lazily
  41. */
  42. public $connected = false;
  43. /**
  44. * @var
  45. */
  46. public $status;
  47. /**
  48. * @var string
  49. */
  50. protected $server;
  51. /**
  52. * @var
  53. */
  54. protected $persistent;
  55. /**
  56. * @var Client
  57. */
  58. private $client;
  59. /**
  60. * @var \MongoDB\Driver\Manager
  61. */
  62. private $manager;
  63. /**
  64. * Creates a new database connection object
  65. *
  66. * @link http://php.net/manual/en/mongo.construct.php
  67. * @param string $server The server name.
  68. * @param array $options An array of options for the connection.
  69. * @param array $driverOptions An array of options for the MongoDB driver.
  70. * @throws MongoConnectionException
  71. */
  72. public function __construct($server = 'default', array $options = ['connect' => true], array $driverOptions = [])
  73. {
  74. if ($server === 'default') {
  75. $server = 'mongodb://' . self::DEFAULT_HOST . ':' . self::DEFAULT_PORT;
  76. }
  77. $this->server = $server;
  78. if (false === strpos($this->server, 'mongodb://')) {
  79. $this->server = 'mongodb://'.$this->server;
  80. }
  81. $this->client = new Client($this->server, $options, $driverOptions);
  82. $info = $this->client->__debugInfo();
  83. $this->manager = $info['manager'];
  84. if (isset($options['connect']) && $options['connect']) {
  85. $this->connect();
  86. }
  87. }
  88. /**
  89. * Closes this database connection
  90. *
  91. * @link http://www.php.net/manual/en/mongoclient.close.php
  92. * @param boolean|string $connection
  93. * @return boolean If the connection was successfully closed.
  94. */
  95. public function close($connection = null)
  96. {
  97. $this->connected = false;
  98. return false;
  99. }
  100. /**
  101. * Connects to a database server
  102. *
  103. * @link http://www.php.net/manual/en/mongoclient.connect.php
  104. *
  105. * @throws MongoConnectionException
  106. * @return boolean If the connection was successful.
  107. */
  108. public function connect()
  109. {
  110. $this->connected = true;
  111. return true;
  112. }
  113. /**
  114. * Drops a database
  115. *
  116. * @link http://www.php.net/manual/en/mongoclient.dropdb.php
  117. * @param mixed $db The database to drop. Can be a MongoDB object or the name of the database.
  118. * @return array The database response.
  119. * @deprecated Use MongoDB::drop() instead.
  120. */
  121. public function dropDB($db)
  122. {
  123. return $this->selectDB($db)->drop();
  124. }
  125. /**
  126. * Gets a database
  127. *
  128. * @link http://php.net/manual/en/mongoclient.get.php
  129. * @param string $dbname The database name.
  130. * @return MongoDB The database name.
  131. */
  132. public function __get($dbname)
  133. {
  134. return $this->selectDB($dbname);
  135. }
  136. /**
  137. * Gets the client for this object
  138. *
  139. * @internal This part is not of the ext-mongo API and should not be used
  140. * @return Client
  141. */
  142. public function getClient()
  143. {
  144. return $this->client;
  145. }
  146. /**
  147. * Get connections
  148. *
  149. * Returns an array of all open connections, and information about each of the servers
  150. *
  151. * @return array
  152. */
  153. public static function getConnections()
  154. {
  155. return [];
  156. }
  157. /**
  158. * Get hosts
  159. *
  160. * This method is only useful with a connection to a replica set. It returns the status of all of the hosts in the
  161. * set. Without a replica set, it will just return an array with one element containing the host that you are
  162. * connected to.
  163. *
  164. * @return array
  165. */
  166. public function getHosts()
  167. {
  168. $this->forceConnect();
  169. $results = [];
  170. try {
  171. $servers = $this->manager->getServers();
  172. } catch (\MongoDB\Driver\Exception\Exception $e) {
  173. throw ExceptionConverter::toLegacy($e);
  174. }
  175. foreach ($servers as $server) {
  176. $key = sprintf('%s:%d;-;.;%d', $server->getHost(), $server->getPort(), getmypid());
  177. $info = $server->getInfo();
  178. switch ($server->getType()) {
  179. case \MongoDB\Driver\Server::TYPE_RS_PRIMARY:
  180. $state = 1;
  181. break;
  182. case \MongoDB\Driver\Server::TYPE_RS_SECONDARY:
  183. $state = 2;
  184. break;
  185. default:
  186. $state = 0;
  187. }
  188. $results[$key] = [
  189. 'host' => $server->getHost(),
  190. 'port' => $server->getPort(),
  191. 'health' => (int) $info['ok'],
  192. 'state' => $state,
  193. 'ping' => $server->getLatency(),
  194. 'lastPing' => null,
  195. ];
  196. }
  197. return $results;
  198. }
  199. /**
  200. * Kills a specific cursor on the server
  201. *
  202. * @link http://www.php.net/manual/en/mongoclient.killcursor.php
  203. * @param string $server_hash The server hash that has the cursor.
  204. * @param int|MongoInt64 $id The ID of the cursor to kill.
  205. * @return bool
  206. */
  207. public function killCursor($server_hash , $id)
  208. {
  209. $this->notImplemented();
  210. }
  211. /**
  212. * Lists all of the databases available
  213. *
  214. * @link http://php.net/manual/en/mongoclient.listdbs.php
  215. * @return array Returns an associative array containing three fields. The first field is databases, which in turn contains an array. Each element of the array is an associative array corresponding to a database, giving the database's name, size, and if it's empty. The other two fields are totalSize (in bytes) and ok, which is 1 if this method ran successfully.
  216. */
  217. public function listDBs()
  218. {
  219. try {
  220. $databaseInfoIterator = $this->client->listDatabases();
  221. } catch (\MongoDB\Driver\Exception\Exception $e) {
  222. throw ExceptionConverter::toLegacy($e);
  223. }
  224. $databases = [
  225. 'databases' => [],
  226. 'totalSize' => 0,
  227. 'ok' => 1.0,
  228. ];
  229. foreach ($databaseInfoIterator as $databaseInfo) {
  230. $databases['databases'][] = [
  231. 'name' => $databaseInfo->getName(),
  232. 'empty' => $databaseInfo->isEmpty(),
  233. 'sizeOnDisk' => $databaseInfo->getSizeOnDisk(),
  234. ];
  235. $databases['totalSize'] += $databaseInfo->getSizeOnDisk();
  236. }
  237. return $databases;
  238. }
  239. /**
  240. * Gets a database collection
  241. *
  242. * @link http://www.php.net/manual/en/mongoclient.selectcollection.php
  243. * @param string $db The database name.
  244. * @param string $collection The collection name.
  245. * @return MongoCollection Returns a new collection object.
  246. * @throws Exception Throws Exception if the database or collection name is invalid.
  247. */
  248. public function selectCollection($db, $collection)
  249. {
  250. return new MongoCollection($this->selectDB($db), $collection);
  251. }
  252. /**
  253. * Gets a database
  254. *
  255. * @link http://www.php.net/manual/en/mongo.selectdb.php
  256. * @param string $name The database name.
  257. * @return MongoDB Returns a new db object.
  258. * @throws InvalidArgumentException
  259. */
  260. public function selectDB($name)
  261. {
  262. return new MongoDB($this, $name);
  263. }
  264. /**
  265. * {@inheritdoc}
  266. */
  267. public function setReadPreference($readPreference, $tags = null)
  268. {
  269. return $this->setReadPreferenceFromParameters($readPreference, $tags);
  270. }
  271. /**
  272. * {@inheritdoc}
  273. */
  274. public function setWriteConcern($wstring, $wtimeout = 0)
  275. {
  276. return $this->setWriteConcernFromParameters($wstring, $wtimeout);
  277. }
  278. /**
  279. * String representation of this connection
  280. *
  281. * @link http://www.php.net/manual/en/mongoclient.tostring.php
  282. * @return string Returns hostname and port for this connection.
  283. */
  284. public function __toString()
  285. {
  286. return $this->server;
  287. }
  288. /**
  289. * Forces a connection by executing the ping command
  290. */
  291. private function forceConnect()
  292. {
  293. $command = new \MongoDB\Driver\Command(['ping' => 1]);
  294. $this->manager->executeCommand('db', $command);
  295. }
  296. private function notImplemented()
  297. {
  298. throw new \Exception('Not implemented');
  299. }
  300. /**
  301. * @return array
  302. */
  303. function __sleep()
  304. {
  305. return [
  306. 'connected', 'status', 'server', 'persistent'
  307. ];
  308. }
  309. }