Skip to content

Commit 5437f68

Browse files
committed
add executeCommand method to Database
1 parent 2b2d8ef commit 5437f68

File tree

3 files changed

+42
-0
lines changed

3 files changed

+42
-0
lines changed

src/Database.php

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -135,6 +135,31 @@ public function dropCollection($collectionName)
135135
return $operation->execute($server);
136136
}
137137

138+
/**
139+
* This is the method to issue database commands.
140+
*
141+
* @param array|object $command A database command to send
142+
* @param ReadPreference|null $readPreference Default read preference to apply
143+
* @return Cursor
144+
*/
145+
public function executeCommand($command, ReadPreference $readPreference = null)
146+
{
147+
if ( ! is_array($command) && ! is_object($command)) {
148+
throw new InvalidArgumentTypeException('"command" parameter', $command, 'array or object');
149+
}
150+
151+
if ( ! $command instanceof Command) {
152+
$command = new Command($command);
153+
}
154+
155+
if ( ! isset($readPreference)) {
156+
$readPreference = $this->readPreference;
157+
}
158+
159+
$server = $this->manager->selectServer($readPreference);
160+
return $server->executeCommand($this->databaseName, $command);
161+
}
162+
138163
/**
139164
* Returns the database name.
140165
*

tests/Database/DatabaseFunctionalTest.php

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
use MongoDB\Driver\BulkWrite;
77
use MongoDB\Driver\ReadPreference;
88
use MongoDB\Driver\WriteConcern;
9+
use MongoDB\Driver\Command;
910

1011
/**
1112
* Functional tests for the Database class.
@@ -77,6 +78,19 @@ public function testDrop()
7778
$this->assertCollectionCount($this->getNamespace(), 0);
7879
}
7980

81+
public function testCommand()
82+
{
83+
$command = new Command(['isMaster' => 1]);
84+
$readPreference = new ReadPreference(ReadPreference::RP_PRIMARY);
85+
$cursor = $this->database->executeCommand($command, $readPreference);
86+
$this->assertInstanceOf('MongoDB\Driver\Cursor', $cursor);
87+
$cursor->setTypeMap(['root' => 'array', 'document' => 'array']);
88+
$document = current($cursor->toArray());
89+
$this->assertCommandSucceeded($document);
90+
$this->assertArrayHasKey('ismaster', $document);
91+
$this->assertTrue($document['ismaster']);
92+
}
93+
8094
public function testSelectCollectionInheritsReadPreferenceAndWriteConcern()
8195
{
8296
$databaseOptions = [

tests/Database/FunctionalTestCase.php

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,9 @@
1010
*/
1111
abstract class FunctionalTestCase extends BaseFunctionalTestCase
1212
{
13+
/**
14+
* @var $database Database
15+
*/
1316
protected $database;
1417

1518
public function setUp()

0 commit comments

Comments
 (0)