Advertisement
Guest User

Mongodb wrapper

a guest
Aug 25th, 2017
101
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 4.43 KB | None | 0 0
  1. <?php
  2.  
  3. namespace app\components;
  4.  
  5. use app\system\Exception;
  6. use yii\base\Component;
  7.  
  8. class MongoHelper extends Component{
  9.  
  10.   protected $mongo;
  11.   public $class;
  12.   public $username;
  13.   public $password;
  14.   public $replica_set;
  15.   public $database;
  16.   public $host;
  17.   /**
  18.    * @var MongoClient
  19.    */
  20.   public $client;
  21.   private $contactsClient ;
  22.  
  23.   protected $contactsCollection = 'associatedContacts';
  24.   protected $countersCollection = 'counters';
  25.   protected $linksCollection = 'contactsLinks';
  26.  
  27.   public function init()
  28.   {
  29.     $host = $this->host;
  30.     $host = is_array($host) ? implode(',', $host) : $host;
  31.  
  32.     $username = $this->username;
  33.     $password = $this->password;
  34.     $replicaSet = $this->replica_set;
  35.  
  36.     if ($replicaSet) {
  37.       $replicaSet = "?replicaSet=" . $replicaSet;
  38.     }
  39.  
  40.     $mongoDbAuth = '';
  41.     if (!empty($username) && !empty($password)) {
  42.       $mongoDbAuth = "{$username}:{$password}@";
  43.     }
  44.     try {
  45.       $this->client = new \MongoDB\Client("mongodb://{$mongoDbAuth}{$host}/{$replicaSet}");
  46.       $this->client = $this->client->{$this->database};
  47.  
  48.       $this->contactsClient = $this->client->{$this->contactsCollection};
  49.     } catch (\Exception $e) {
  50.       return [
  51.         'result' => 5004,
  52.       ];
  53.     }
  54.  
  55.   }
  56.  
  57.   public function insert($data)
  58.   {
  59.     if(!empty($data)) {
  60.       return $this->contactsClient->insertOne($data);
  61.     } else {
  62.       throw new \Exception('Empty data', 400);
  63.     }
  64.   }
  65.   /**
  66.    * Find many documents
  67.    *
  68.    * @param array $query
  69.    * @param array $fields
  70.    * @return MongoCursor
  71.    */
  72.   public function find(array $query = array(), array $fields = array())
  73.   {
  74.     return $this->contactsClient->find($query, $fields);
  75.   }
  76.  
  77.   public function findOne(array $query = array(), array $fields = array())
  78.   {
  79.     return $this->contactsClient->findOne($query, $fields);
  80.   }
  81.   /**
  82.    * @param $collectionName
  83.    * @return MongoCollection
  84.    */
  85.   public function getCollection($collectionName = null)
  86.   {
  87.     $collectionName = $collectionName ? $collectionName : $this->collection;
  88.  
  89.     if (!($this->client instanceof \MongoDB\Client)) {
  90.       $this->connect($this->defaultConfig);
  91.     }
  92.     return $this->client
  93.       ->selectDB($this->mongoDb)
  94.       ->selectCollection($collectionName);
  95.   }
  96.  
  97.   public function getNextSequenceValue($id)
  98.   {
  99.     $countersCollectionExist = false;
  100.     //ищем есть ли коллекция для сиквенсов countersCollection
  101.     foreach ($this->client->listCollections() as $collectionInfo) {
  102.       if($collectionInfo->getName() == $this->countersCollection) {
  103.         $sequenceCollection = $this->client->{$this->countersCollection};
  104.         $countersCollectionExist = true;
  105.         break;
  106.       }
  107.     }
  108.     if(!$countersCollectionExist) {
  109.       $this->client->{$this->countersCollection}->insertOne(
  110.         [
  111.           '_id'      => "internal_id",
  112.           'sequence' => 0
  113.         ]
  114.       );
  115.       $sequenceCollection = $this->client->{$this->countersCollection};
  116.     }
  117.  
  118.     $sequenceDoc = $sequenceCollection->findOneAndUpdate(
  119.       ['_id' => $id],
  120.       ['$inc' => ['sequence' => 1]],
  121.       ['returnDocument' => \MongoDB\Operation\FindOneAndUpdate::RETURN_DOCUMENT_AFTER]
  122.     );
  123.     $nextSequence = $sequenceDoc->bsonSerialize()->sequence;
  124.  
  125.     return $nextSequence;
  126.   }
  127.  
  128.   public function updateContacts($groupId1, $groupId2)
  129.   {
  130.     if (!empty($groupId1) AND !empty($groupId2)) {
  131.       $updateResult = $this->contactsClient->updateMany(
  132.         /*[
  133.           '$or' => [
  134.             ['group_id' => $groupId1],
  135.             ['group_id' => $groupId2],
  136.           ]
  137.         ],*/
  138.         ['group_id' => $groupId2],
  139.         [
  140.           '$set' => ['group_id' => $groupId1] // В Contacts для всех записей, где group_id=contact2.group_id ставим group_id = contact1.group_id
  141.         ]
  142.       );
  143.       return $updateResult;
  144.     } else {
  145.       throw new \Exception('Empty data', 400);
  146.     }
  147.   }
  148.  
  149.   public function addLinks($internalId1, $internalId2)
  150.   {
  151.     if (!empty($internalId1) AND !empty($internalId2)) {
  152.       return  $this->contactsClient->insertOne(
  153.         [
  154.           'id1' => $internalId1,
  155.           'id2' => $internalId2
  156.         ]
  157.       );
  158.     } else {
  159.       throw new \Exception('Empty data', 400);
  160.     }
  161.   }
  162.  
  163.   public function __call($name, $arguments)
  164.   {
  165.     return call_user_func_array([$this->contactsClient, $name], $arguments);
  166.   }
  167.  
  168. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement