config = $config; // Build the connection string $dsn = $this->getDsn($config); // You can pass options directly to the MongoDB constructor $options = $config['options'] ?? []; // Resolve these before createConnection(): the automatic encryption // options key the encrypted fields map and name the alternate keys. $this->database = $this->getDefaultDatabaseName($dsn, $config); $this->tablePrefix = $config['prefix'] ?? ''; // Create the connection $this->connection = $this->createConnection($dsn, $config, $options); // Select database $this->db = $this->connection->getDatabase($this->database); $this->useDefaultPostProcessor(); $this->useDefaultSchemaGrammar(); $this->useDefaultQueryGrammar(); $this->renameEmbeddedIdField = $config['rename_embedded_id_field'] ?? true; } /** * Whether automatic encryption is configured, and whether the given * collection is declared in the encryptedFieldsMap. * * @param string|null $collection The logical collection name, without the table prefix. */ public function isAutoEncryptionEnabled(?string $collection = null): bool { return $this->encryption()->isAutoEncryptionEnabled($collection); } /** * The client-side encryption object, to encrypt an expression or manage * data keys outside the query path. * * @throws InvalidArgumentException When Queryable Encryption is not configured on this connection. */ public function getClientEncryption(): ClientEncryption { return $this->encryption()->getClientEncryption(); } /** * Queryable Encryption support of this connection. * * @internal Use isAutoEncryptionEnabled() and getClientEncryption() instead. */ public function encryption(): AutoEncryption { return $this->autoEncryption ??= new AutoEncryption($this, $this->getDsn($this->config), $this->config); } /** * Begin a fluent query against a database collection. * * @param string $table The name of the MongoDB collection * @param string|null $as Ignored. Not supported by MongoDB * * @return Query\Builder */ #[Override] public function table($table, $as = null) { $query = new Query\Builder($this, $this->getQueryGrammar(), $this->getPostProcessor()); return $query->from($table); } /** * Get a MongoDB collection. * * @param string $name The logical collection name. The connection table prefix is applied. * * @return Collection */ public function getCollection($name): Collection { $this->syncCommandSubscriber(); return $this->db->getCollection($this->tablePrefix . $name); } /** @inheritdoc */ #[Override] public function getSchemaBuilder() { return new Schema\Builder($this); } /** * Get the MongoDB database object. * * @deprecated since mongodb/laravel-mongodb:5.2, use getDatabase() instead * * @return Database */ public function getMongoDB() { trigger_error(sprintf('Since mongodb/laravel-mongodb:5.2, Method "%s()" is deprecated, use "getDatabase()" instead.', __FUNCTION__), E_USER_DEPRECATED); return $this->db; } /** * Get the MongoDB database object. * * @param string|null $name Name of the database, if not provided the default database will be returned. * * @return Database */ public function getDatabase(?string $name = null): Database { $this->syncCommandSubscriber(); if ($name && $name !== $this->database) { return $this->connection->getDatabase($name); } return $this->db; } /** * Return MongoDB object. * * @deprecated since mongodb/laravel-mongodb:5.2, use getClient() instead * * @return Client */ public function getMongoClient() { trigger_error(sprintf('Since mongodb/laravel-mongodb:5.2, method "%s()" is deprecated, use "getClient()" instead.', __FUNCTION__), E_USER_DEPRECATED); return $this->getClient(); } /** * Get the MongoDB client. */ public function getClient(): ?Client { $this->syncCommandSubscriber(); return $this->connection; } /** @inheritdoc */ #[Override] public function enableQueryLog() { parent::enableQueryLog(); $this->syncCommandSubscriber(); } #[Override] public function disableQueryLog() { parent::disableQueryLog(); $this->syncCommandSubscriber(); } #[Override] protected function withFreshQueryLog($callback) { try { return parent::withFreshQueryLog($callback); } finally { // The parent method enable query log using enableQueryLog() // but disables it by setting $loggingQueries to false. We need to // remove the subscriber when nothing else consumes the query events. if (! $this->loggingQueries) { $this->disableQueryLog(); } } } /** * Get the name of the default database based on db config or try to detect it from dsn. * * @throws InvalidArgumentException */ protected function getDefaultDatabaseName(string $dsn, array $config): string { if (empty($config['database'])) { if (! preg_match('/^mongodb(?:[+]srv)?:\\/\\/.+?\\/([^?&]+)/s', $dsn, $matches)) { throw new InvalidArgumentException('Database is not properly configured.'); } $config['database'] = $matches[1]; } return $config['database']; } /** * Create a new MongoDB connection. */ protected function createConnection(string $dsn, array $config, array $options): Client { // By default driver options is an empty array. $driverOptions = []; if (isset($config['driver_options']) && is_array($config['driver_options'])) { $driverOptions = $config['driver_options']; } $driverOptions['driver'] = [ 'name' => 'laravel-mongodb', 'version' => self::getVersion(), ]; // Check if the credentials are not already set in the options if (! isset($options['username']) && ! empty($config['username'])) { $options['username'] = $config['username']; } if (! isset($options['password']) && ! empty($config['password'])) { $options['password'] = $config['password']; } if (isset($config['name'])) { $driverOptions += ['connectionName' => $config['name']]; } $driverOptions = $this->encryption()->prepareDriverOptions($driverOptions); return new Client($dsn, $options, $driverOptions); } /** * Check the connection to the MongoDB server * * @throws ConnectionException if connection to the server fails (for reasons other than authentication). * @throws AuthenticationException if authentication is needed and fails. * @throws RuntimeException if a server matching the read preference could not be found. */ public function ping(): void { $this->getClient()->getManager()->selectServer(new ReadPreference(ReadPreference::PRIMARY_PREFERRED)); } /** @inheritdoc */ public function disconnect() { $this->disableQueryLog(); // The client outlives the connection, so detach the subscriber explicitly. if ($this->connection !== null && $this->commandSubscriber !== null) { $this->connection->removeSubscriber($this->commandSubscriber); } // The rebuilt connection can use another encryption configuration. EncryptedFieldTypes::clearCache(); $this->commandSubscriber = null; $this->connection = null; $this->supportsRelationLookup = null; } /** * Determine if the given configuration array has a dsn string. * * @deprecated */ protected function hasDsnString(array $config): bool { return ! empty($config['dsn']); } /** * Get the DSN string form configuration. */ protected function getDsnString(array $config): string { return $config['dsn']; } /** * Get the DSN string for a host / port configuration. */ protected function getHostDsn(array $config): string { // Treat host option as array of hosts $hosts = is_array($config['host']) ? $config['host'] : [$config['host']]; foreach ($hosts as &$host) { // ipv6 if (filter_var($host, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6)) { $host = '[' . $host . ']'; if (! empty($config['port'])) { $host .= ':' . $config['port']; } } else { // Check if we need to add a port to the host if (! str_contains($host, ':') && ! empty($config['port'])) { $host .= ':' . $config['port']; } } } // Check if we want to authenticate against a specific database. $authDatabase = isset($config['options']) && ! empty($config['options']['database']) ? $config['options']['database'] : null; return 'mongodb://' . implode(',', $hosts) . ($authDatabase ? '/' . $authDatabase : ''); } /** * Create a DSN string from a configuration. */ protected function getDsn(array $config): string { if (! empty($config['dsn'])) { return $this->getDsnString($config); } if (! empty($config['host'])) { return $this->getHostDsn($config); } throw new InvalidArgumentException('MongoDB connection configuration requires "dsn" or "host" key.'); } /** @inheritdoc */ #[Override] public function getDriverName() { return 'mongodb'; } /** @inheritdoc */ public function getDriverTitle() { return 'MongoDB'; } /** @inheritdoc */ #[Override] protected function getDefaultPostProcessor() { return new Query\Processor(); } /** @inheritdoc */ #[Override] protected function getDefaultQueryGrammar() { return new Query\Grammar($this); } /** @inheritdoc */ #[Override] protected function getDefaultSchemaGrammar() { return new Schema\Grammar($this); } /** * Set database. */ public function setDatabase(Database $db) { $this->db = $db; } /** @inheritdoc */ public function threadCount() { $status = $this->db->command(['serverStatus' => 1])->toArray(); return $status[0]['connections']['current']; } /** * Dynamically pass methods to the connection. * * @param string $method * @param array $parameters * * @return mixed */ public function __call($method, $parameters) { // Methods of the database object run commands, too. $this->syncCommandSubscriber(); return $this->db->$method(...$parameters); } /** Set whether to rename "id" field into "_id" for embedded documents. */ public function setRenameEmbeddedIdField(bool $rename): void { $this->renameEmbeddedIdField = $rename; } /** Get whether to rename "id" field into "_id" for embedded documents. */ public function getRenameEmbeddedIdField(): bool { return $this->renameEmbeddedIdField; } /** * Supports the Filament bridge. * * @internal */ public function supportsRelationLookup(): bool { return $this->supportsRelationLookup ??= $this->maxWireVersion() >= self::WIRE_VERSION_FOR_RELATION_LOOKUP; } private function maxWireVersion(): int { $server = $this->getClient()->getManager()->selectServer(new ReadPreference(ReadPreference::PRIMARY_PREFERRED)); return (int) ($server->getInfo()['maxWireVersion'] ?? 0); } /** * Return the server version of one of the MongoDB servers: primary for * replica sets and standalone, and the selected server for sharded clusters. * * @internal */ public function getServerVersion(): string { return $this->db->command(['buildInfo' => 1])->toArray()[0]['version']; } /** Whether something consumes the query events: the query log or a listener. */ private function isQueryWatched(): bool { return $this->loggingQueries || (bool) $this->events?->hasListeners(QueryExecuted::class); } /** * Attach or detach the command subscriber to match the consumers of the * query events, so that MongoDB connections report commands like SQL * connections do. * * @internal Called by the query builders before running a command. */ public function syncCommandSubscriber(): void { if ($this->connection === null) { return; } if (! $this->isQueryWatched()) { // The consumer may have been removed since the previous command. $this->detachCommandSubscriber(); return; } if ($this->commandSubscriber === null) { $this->commandSubscriber = new CommandSubscriber($this); $this->connection->addSubscriber($this->commandSubscriber); } } /** Detach the command subscriber when nothing consumes the query events. */ private function detachCommandSubscriber(): void { if ($this->commandSubscriber === null || $this->isQueryWatched()) { return; } $this->connection->removeSubscriber($this->commandSubscriber); $this->commandSubscriber = null; } public static function getVersion(): string { return self::$version ?? self::lookupVersion(); } private static function lookupVersion(): string { try { try { return self::$version = InstalledVersions::getPrettyVersion('mongodb/laravel-mongodb') ?? 'unknown'; } catch (OutOfBoundsException) { return self::$version = InstalledVersions::getPrettyVersion('jenssegers/mongodb') ?? 'unknown'; } } catch (Throwable) { return self::$version = 'error'; } } }