DatabaseFactory.php in MongoDB 8.2
File
modules/mongodb/src/DatabaseFactory.php
View source
<?php
declare (strict_types=1);
namespace Drupal\mongodb;
use Drupal\Component\Render\FormattableMarkup;
use Drupal\Core\Site\Settings;
class DatabaseFactory {
protected $clientFactory;
protected $settings;
public function __construct(ClientFactory $clientFactory, Settings $settings) {
$this->clientFactory = $clientFactory;
$this->settings = $settings
->get('mongodb')['databases'];
}
public function get($dbAlias) {
if (!isset($this->settings[$dbAlias])) {
throw new \InvalidArgumentException((new FormattableMarkup('Nonexistent database alias: @alias', [
'@alias' => $dbAlias,
]))
->__toString());
}
try {
list($clientAlias, $database) = $this->settings[$dbAlias];
$client = $this->clientFactory
->get($clientAlias);
$result = $client
->selectDatabase($database);
} catch (\InvalidArgumentException $e) {
$result = NULL;
}
return $result;
}
public function nextId($sequenceId = 'sequences', $value = 0) {
$collection = $this
->get('default')
->selectCollection('sequences');
$sequenceSelector = [
'_id' => $sequenceId,
];
if ($value) {
$selector = $sequenceSelector + [
'value' => [
'$lt' => $value,
],
];
$update = [
'$set' => [
'value' => $value,
],
];
$collection
->updateOne($selector, $update);
}
$update = [
'$inc' => [
'value' => 1,
],
];
$options = [
'upsert' => TRUE,
'returnDocument' => FindOneAndUpdate::RETURN_DOCUMENT_AFTER,
];
$document = $collection
->findOneAndUpdate($sequenceSelector, $update, $options);
$result = $document->value ?? 1;
return $result;
}
}
Classes
Name |
Description |
DatabaseFactory |
Helper class to construct a MongoDB Database with Drupal specific config. |