/**
  * Count collection.
  *
  * @param string $table
  * @param array  $query
  *
  * @return int
  */
 private function count($table, array $query = array())
 {
     $command = new Command(array('count' => $table, 'query' => $query));
     $cursor = $this->conn->executeCommand($this->db, $command);
     $results = (array) current($cursor->toArray());
     return (int) $results['n'];
 }
 /**
  * Forces a connection by executing the ping command
  */
 private function forceConnect()
 {
     $command = new \MongoDB\Driver\Command(['ping' => 1]);
     $this->manager->executeCommand('db', $command);
 }
 public function analyzeTableDecisions($table_id, $variant_id)
 {
     $table = $this->read($table_id);
     $mongo = new Manager(sprintf("mongodb://%s:%d", env('DB_HOST'), env('DB_PORT')));
     $query = new Query(['table._id' => new ObjectID($table_id), 'table.variant._id' => new ObjectId($variant_id), 'applications' => ApplicationableHelper::getApplicationId(), 'created_at' => ['$gte' => new UTCDatetime($table->updated_at->timestamp * 1000)]], ['projection' => ['rules' => 1]]);
     $decisions = $mongo->executeQuery(env('DB_DATABASE') . '.' . (new Decision())->getTable(), $query)->toArray();
     $map = [];
     if (($decisionsAmount = count($decisions)) > 0) {
         foreach ($decisions as $decision) {
             $rules = $decision->rules;
             foreach ($rules as $rule) {
                 if (!isset($rule->_id)) {
                     # ignore old decisions without Rule._id
                     continue;
                 }
                 $ruleIndex = strval($rule->_id);
                 foreach ($rule->conditions as $condition) {
                     $index = "{$ruleIndex}@" . strval($condition->_id);
                     if (!isset($map[$index])) {
                         $map[$index] = ['matched' => 0, 'requests' => 0];
                     }
                     if ($condition->matched === true) {
                         $map[$index]['matched']++;
                     }
                     $map[$index]['requests']++;
                 }
                 if (!isset($map[$ruleIndex])) {
                     $map[$ruleIndex] = ['matched' => 0, 'requests' => 0];
                 }
                 $map[$ruleIndex]['requests']++;
                 if ($rule->than === $rule->decision) {
                     $map[$ruleIndex]['matched']++;
                 }
             }
         }
     }
     $variant = $table->getVariantForCheck($variant_id);
     foreach ($variant->rules as $rule) {
         $ruleIndex = $rule->_id;
         foreach ($rule->conditions as $condition) {
             $index = "{$ruleIndex}@" . strval($condition->_id);
             if (array_key_exists($index, $map)) {
                 $condition->probability = round($map[$index]['matched'] / $map[$index]['requests'], 5);
             } else {
                 $condition->probability = null;
             }
             $condition->requests = array_key_exists($index, $map) ? $map[$index]['requests'] : 0;
             $rule->conditions()->associate($condition);
         }
         $ruleHasRequests = array_key_exists($ruleIndex, $map);
         $rule->probability = $ruleHasRequests ? round($map[$ruleIndex]['matched'] / $map[$ruleIndex]['requests'], 5) : 0;
         $rule->requests = $ruleHasRequests ? $map[$ruleIndex]['requests'] : 0;
         $variant->rules()->associate($rule);
     }
     $clonedTable = clone $table;
     $clonedTable->variants = [];
     $clonedTable->variants()->associate($variant);
     return $clonedTable;
 }
 protected function setUp()
 {
     if (!class_exists('MongoDB\\Collection')) {
         self::markTestSkipped("MongoDB library not found.");
     }
     try {
         self::$manager->selectServer(self::$manager->getReadPreference());
     } catch (\Exception $e) {
         self::markTestSkipped($e->getMessage());
     }
     self::$collection = new Collection(self::$manager, self::$testDb, self::$testCollection);
 }
Beispiel #5
0
 /**
  * Constructor.
  *
  * @param Client|Manager $mongodb    MongoDB library or driver client
  * @param string         $database   Database name
  * @param string         $collection Collection name
  * @param int            $level      The minimum logging level at which this handler will be triggered
  * @param Boolean        $bubble     Whether the messages that are handled can bubble up the stack or not
  */
 public function __construct($mongodb, $database, $collection, $level = Logger::DEBUG, $bubble = true)
 {
     if (!($mongodb instanceof Client || $mongodb instanceof Manager)) {
         throw new \InvalidArgumentException('MongoDB\\Client or MongoDB\\Driver\\Manager instance required');
     }
     if ($mongodb instanceof Client) {
         $this->collection = $mongodb->selectCollection($database, $collection);
     } else {
         $this->manager = $mongodb;
         $this->namespace = $database . '.' . $collection;
     }
     parent::__construct($level, $bubble);
 }
/**
 * Returns a WriteConcern corresponding to the Manager's write concern.
 *
 * @internal
 * @todo this function can be removed once PHPC-417 is implemented
 * @param Manager $manager
 * @return WriteConcern
 */
function get_manager_write_concern(Manager $manager)
{
    $wc = $manager->getWriteConcern();
    if ($wc instanceof WriteConcern) {
        return $wc;
    }
    $args = array(isset($wc['w']) ? $wc['w'] : -2, $wc['wtimeout']);
    if (isset($wc['journal'])) {
        $args[] = $wc['journal'];
        if (isset($wc['fsync'])) {
            $args[] = $wc['fsync'];
        }
    }
    $rc = new ReflectionClass('MongoDB\\Driver\\WriteConcern');
    return $rc->newInstanceArgs($args);
}
 /**
  * Executes a bulk write to MongoDB, wrapping exceptions.
  *
  * @param \MongoDB\Driver\BulkWrite $bulk
  * @return \MongoDB\Driver\WriteResult the write result
  * @throws Swift_IoException if things go wrong
  */
 protected function write(\MongoDB\Driver\BulkWrite $bulk)
 {
     try {
         return $this->manager->executeBulkWrite($this->collection, $bulk, $this->wc);
     } catch (\Exception $e) {
         throw new Swift_IoException("Could not update email sent on date", 0, $e);
     }
 }
Beispiel #8
0
 /**
  * Write a message to the log.
  *
  * @param array $event Event data
  * @return void
  * @throws Exception\RuntimeException
  */
 protected function doWrite(array $event)
 {
     if (null === $this->manager) {
         throw new Exception\RuntimeException('MongoDB\\Driver\\Manager must be defined');
     }
     if (isset($event['timestamp']) && $event['timestamp'] instanceof DateTimeInterface) {
         $millis = (int) floor((double) $event['timestamp']->format('U.u') * 1000);
         $event['timestamp'] = new UTCDateTime($millis);
     }
     $bulkWrite = new BulkWrite();
     $bulkWrite->insert($event);
     $this->manager->executeBulkWrite($this->database, $bulkWrite, $this->writeConcern);
 }
 /**
  * Execute mongodb query.
  *
  * @param Query  $query
  * @param string $namespace
  *
  * @return DomainEventStream|null
  */
 private function query(Query $query, $namespace)
 {
     $cursor = $this->conn->executeQuery($namespace, $query);
     $cursor->setTypeMap(array('document' => 'array'));
     $results = $cursor->toArray();
     $events = array();
     if (count($results)) {
         foreach ($results as $record) {
             $events[] = $this->deserialize((array) $record);
         }
         return new DomainEventStream($events);
     }
     return null;
 }
Beispiel #10
0
 /**
  * {@inheritdoc}
  */
 public function getStatus()
 {
     try {
         // Create a manager and try to get servers
         $manager = new Manager($this->params['server']);
         $manager->executeCommand($this->params['databaseName'], new Command(['ping' => 1]));
         return true;
     } catch (MongoException $e) {
         return false;
     }
 }
Beispiel #11
0
<?php

use MongoDB\Driver\Manager;
use MongoDB\Driver\Query;
use MongoDB\Driver\Command;
$dsn = "mongodb://localhost:27017/users";
$options = ['username' => 'admin', 'password' => 'public'];
$manager = new Manager($dsn, $options);
$query = new Query(['city' => '北京市'], ['limit' => 5]);
$count = ['count' => 'usergeo', 'query' => ['city' => '北京市']];
$aggregate = ['aggregate' => 'usergeo', 'pipeline' => [['$match' => ['city' => '北京市']], ['$group' => ['_id' => null, 'avg_time' => ['$avg' => '$created_at']]]]];
try {
    /* Specify the full namespace as the first argument, followed by the query
     * object and an optional read preference. MongoDB\Driver\Cursor is returned
     * success; otherwise, an exception is thrown. */
    $cursor = $manager->executeQuery("users.usergeo", $query);
    // Iterate over all matched documents
    $array = iterator_to_array($cursor);
    foreach ($array as $key => $value) {
        $value = (array) $value;
        var_dump($value['city']);
        var_dump($value['province']);
    }
    // count command
    $command = new Command($count);
    $result = $manager->executeCommand("users", $command);
    $response = $result->toArray();
    var_dump($response);
    // aggregate
    $command = new Command($aggregate);
    $result = $manager->executeCommand("users", $command);