105 lines
2.6 KiB
PHP
105 lines
2.6 KiB
PHP
<?php
|
|
|
|
namespace KTXC\Db;
|
|
|
|
use MongoDB\Database as MongoDatabase;
|
|
|
|
/**
|
|
* Wrapper for MongoDB\Database
|
|
* Provides abstraction layer for MongoDB database operations
|
|
*/
|
|
class Database
|
|
{
|
|
private MongoDatabase $database;
|
|
|
|
public function __construct(MongoDatabase $database)
|
|
{
|
|
$this->database = $database;
|
|
}
|
|
|
|
/**
|
|
* Select a collection
|
|
*
|
|
* @param string $collectionName Collection name
|
|
* @param array $options Collection options
|
|
* @return Collection
|
|
*/
|
|
public function selectCollection(string $collectionName, array $options = []): Collection
|
|
{
|
|
$mongoCollection = $this->database->selectCollection($collectionName, $options);
|
|
return new Collection($mongoCollection);
|
|
}
|
|
|
|
/**
|
|
* List collections
|
|
*/
|
|
public function listCollections(array $options = []): array
|
|
{
|
|
$collections = [];
|
|
foreach ($this->database->listCollections($options) as $collectionInfo) {
|
|
$collections[] = $collectionInfo;
|
|
}
|
|
return $collections;
|
|
}
|
|
|
|
/**
|
|
* Drop the database
|
|
*/
|
|
public function drop(array $options = []): array|object|null
|
|
{
|
|
return $this->database->drop($options);
|
|
}
|
|
|
|
/**
|
|
* Get database name
|
|
*/
|
|
public function getDatabaseName(): string
|
|
{
|
|
return $this->database->getDatabaseName();
|
|
}
|
|
|
|
/**
|
|
* Create a collection
|
|
*/
|
|
public function createCollection(string $collectionName, array $options = []): Collection|null
|
|
{
|
|
$mongoCollection = $this->database->createCollection($collectionName, $options);
|
|
return $mongoCollection ? new Collection($mongoCollection) : null;
|
|
}
|
|
|
|
/**
|
|
* Drop a collection
|
|
*/
|
|
public function dropCollection(string $collectionName, array $options = []): array|object|null
|
|
{
|
|
return $this->database->dropCollection($collectionName, $options);
|
|
}
|
|
|
|
/**
|
|
* Execute a database command
|
|
*/
|
|
public function command(array|object $command, array $options = []): Cursor
|
|
{
|
|
/** @var \Iterator $cursor */
|
|
$cursor = $this->database->command($command, $options);
|
|
return new Cursor($cursor);
|
|
}
|
|
|
|
/**
|
|
* Get the underlying MongoDB Database
|
|
* Use sparingly - prefer using wrapper methods
|
|
*/
|
|
public function getMongoDatabase(): MongoDatabase
|
|
{
|
|
return $this->database;
|
|
}
|
|
|
|
/**
|
|
* Magic method to access collection as property
|
|
*/
|
|
public function __get(string $collectionName): Collection
|
|
{
|
|
return $this->selectCollection($collectionName);
|
|
}
|
|
}
|