Skip to content

Commit 0cd9709

Browse files
tuyakhovjmikola
authored andcommitted
PHPLIB-153: Add Database::command() helper
1 parent ae97a8d commit 0cd9709

File tree

2 files changed

+49
-0
lines changed

2 files changed

+49
-0
lines changed

src/Database.php

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -92,6 +92,32 @@ public function __toString()
9292
return $this->databaseName;
9393
}
9494

95+
/**
96+
* Execute a command on this database.
97+
*
98+
* @param array|object $command Command document
99+
* @param ReadPreference|null $readPreference Read preference
100+
* @return Cursor
101+
*/
102+
public function command($command, ReadPreference $readPreference = null)
103+
{
104+
if ( ! is_array($command) && ! is_object($command)) {
105+
throw new InvalidArgumentTypeException('$command', $command, 'array or object');
106+
}
107+
108+
if ( ! $command instanceof Command) {
109+
$command = new Command($command);
110+
}
111+
112+
if ( ! isset($readPreference)) {
113+
$readPreference = $this->readPreference;
114+
}
115+
116+
$server = $this->manager->selectServer($readPreference);
117+
118+
return $server->executeCommand($this->databaseName, $command);
119+
}
120+
95121
/**
96122
* Create a new collection explicitly.
97123
*

tests/Database/DatabaseFunctionalTest.php

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -64,6 +64,29 @@ public function getGetDatabaseName()
6464
$this->assertEquals($this->getDatabaseName(), $this->database->getDatabaseName());
6565
}
6666

67+
public function testCommand()
68+
{
69+
$command = ['isMaster' => 1];
70+
$readPreference = new ReadPreference(ReadPreference::RP_PRIMARY);
71+
$cursor = $this->database->command($command, $readPreference);
72+
73+
$this->assertInstanceOf('MongoDB\Driver\Cursor', $cursor);
74+
$commandResult = current($cursor->toArray());
75+
76+
$this->assertCommandSucceeded($commandResult);
77+
$this->assertTrue(isset($commandResult->ismaster));
78+
$this->assertTrue($commandResult->ismaster);
79+
}
80+
81+
/**
82+
* @expectedException MongoDB\Exception\InvalidArgumentTypeException
83+
* @dataProvider provideInvalidDocumentValues
84+
*/
85+
public function testCommandCommandArgumentTypeCheck($command)
86+
{
87+
$this->database->command($command);
88+
}
89+
6790
public function testDrop()
6891
{
6992
$bulkWrite = new BulkWrite();

0 commit comments

Comments
 (0)