Created
September 8, 2017 22:51
-
-
Save lpj145/a99267f540c13eca22d8d7d9f0698219 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace FiremonPHP\Manager; | |
use MongoDB\Driver\BulkWrite; | |
use MongoDB\Driver\Cursor; | |
use MongoDB\Driver\Query; | |
use MongoDB\Driver\WriteResult; | |
class Manager | |
{ | |
/** | |
* @var \MongoDB\Driver\Manager | |
*/ | |
private $_manager; | |
/** | |
* @var string | |
*/ | |
private $_alias; | |
/** | |
* @var \MongoDB\Driver\BulkWrite[] | |
*/ | |
private $_bulks = []; | |
/** | |
* @var WriteResult[] | |
*/ | |
private $writeResults = []; | |
public function __construct(\MongoDB\Driver\Manager $manager, string $databaseName) | |
{ | |
$this->_manager = $manager; | |
$this->_alias = $databaseName; | |
} | |
/** | |
* Execute all bulk queries | |
* @return WriteResult[] | |
*/ | |
public function execute() | |
{ | |
$self = $this; | |
array_walk($this->_bulks, function(BulkWrite $write, $collectionName) use(&$self) { | |
$self->writeResults[$collectionName] = $self->_manager->executeBulkWrite($self->_alias.'.'.$collectionName, $write); | |
}); | |
return $self->writeResults; | |
} | |
/** | |
* @param string $collection | |
* @param array $data | |
*/ | |
public function insert(string $collection, array $data) | |
{ | |
$bulk = $this->getWrites($collection); | |
$bulk->insert($data); | |
} | |
/** | |
* @param string $collection | |
* @param array $data | |
* @param array $conditions | |
* @param array $options | |
*/ | |
public function update(string $collection, array $data, array $conditions, array $options = []) | |
{ | |
$bulk = $this->getWrites($collection); | |
$bulk->update($conditions, ['$set' => $data], $options); | |
} | |
/** | |
* @param string $collection | |
* @param array $conditions | |
*/ | |
public function delete(string $collection, array $conditions, array $options = ['limit' => 1]) | |
{ | |
$bulk = $this->getWrites($collection); | |
$bulk->delete($conditions, $options); | |
} | |
/** | |
* @param string $collection | |
* @param array $conditions | |
* @param array $options | |
* @return \MongoDB\Driver\Cursor | |
*/ | |
public function find(string $collection, array $conditions, array $options = []): Cursor | |
{ | |
$query = new Query($conditions, $options); | |
return $this->_manager->executeQuery($this->_alias.'.'.$collection, $query); | |
} | |
/** | |
* @param string $collectionName | |
* @return BulkWrite | |
*/ | |
private function getWrites(string $collectionName) | |
{ | |
return $this->_bulks[$collectionName] ?? $this->_bulks[$collectionName] = new BulkWrite(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment