MongoClient.php 9.5 KB

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