Merge pull request #7 from utopia-php/release

Mongo release changes
This commit is contained in:
Shmuel Fogel authored and GitHub committed 2022-11-08 13:58:46 +02:00
commit 62f9a9c020
17 files changed
+543 -194

No files matched your search

+17
View File
@@ -0,0 +1,17 @@
language: php
php: 8.0
services:
- docker
notifications:
email:
- team@appwrite.io
before_script:
- composer install --ignore-platform-reqs
script:
- docker-compose up -d
- docker-compose exec tests vendor/bin/pint --test
- docker-compose exec tests vendor/bin/phpstan analyse
- docker-compose exec tests vendor/bin/phpunit
+80 -1
View File
@@ -1 +1,80 @@
# mongo
# Non-Blocking PHP Line Protocol Client for MongoDB
[![Build Status](https://travis-ci.com/utopia-php/system.svg?branch=main)](https://travis-ci.com/utopia-php/mongo)
![Total Downloads](https://img.shields.io/packagist/dt/utopia-php/mongo.svg)
[![Discord](https://img.shields.io/discord/564160730845151244?label=discord)](https://appwrite.io/discord)
A non-blocking PHP client based on the line protocol for MongoDB. Designed to work well in async PHP environments like [Swoole](https://github.com/swoole/swoole-src)
This library is aiming to be as simple and easy to learn and use.
This library is maintained by the [Appwrite team](https://appwrite.io).
## Getting Started
Install using composer:
```bash
composer require utopia-php/mongo
```
Init in your application:
```php
<?php
$client = new Client('testing', 'mongo', 27017, 'root', 'example', false);
$client->connect();
// drop database
$client->dropDatabase([]);
// Create a new collection
$client->createCollection('movies');
// Get the list of databases
$client->listDatabaseNames()->databases;
// insert a new document
$document = $client->insert('movies', [
'name' => 'Armageddon 1',
'country' => 'USA',
'language' => 'English'
]
);
$id = (string)$document['_id'];
// Find Document with ObjectId
$client->find('movies', ['_id' => new ObjectId($id)])->cursor->firstBatch ?? [];
// insert a new document with specific id
$id = 999;
$client->insert('movies', [
'name' => 'Armageddon 2',
'_id' => $id,
'array' => ['USA', 'UK', 'India'],
'language' => 'English',
'float' => 9.9,
'integer' => 9,
'is_open' => true,
'date_string' => (new \DateTime())->format('Y-m-d\TH:i:s.vP'),
]
);
// Find document by id
$client->find('movies', ['_id' => $id])->cursor->firstBatch ?? [];
// Find documents by field
$client->find('movies', ['name' => 'Armageddon'])->cursor->firstBatch ?? [];
// Delete a document
$client->delete('movies', ['_id' => $id]);
// drop a collections
$client->dropCollection('movies');
```
## System Requirements
Utopia Mongo client requires PHP 8.0 or later. We recommend using the latest PHP version whenever possible.
## Copyright and license
The MIT License (MIT) [http://www.opensource.org/licenses/mit-license.php](http://www.opensource.org/licenses/mit-license.php)
+9 -1
View File
@@ -21,6 +21,12 @@
"autoload-dev": {
"psr-4": {"Utopia\\Tests\\": "tests"}
},
"scripts":{
"test": "phpunit",
"analyse": "vendor/bin/phpstan analyse",
"format": "vendor/bin/pint",
"lint": "vendor/bin/pint --test"
},
"require": {
"php": ">=8.0",
"ext-mongodb": "*",
@@ -29,6 +35,8 @@
"require-dev": {
"fakerphp/faker": "^1.14",
"phpunit/phpunit": "^9.4",
"swoole/ide-helper": "4.8.0"
"swoole/ide-helper": "4.8.0",
"laravel/pint": "1.2.*",
"phpstan/phpstan": "1.8.*"
}
}
Generated
+141 -16
View File
@@ -4,7 +4,7 @@
"Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies",
"This file is @generated automatically"
],
"content-hash": "83cb82fa3af1f298f22d6e1b341453d4",
"content-hash": "ba5d5c5efdbd54c4c986193c090b1760",
"packages": [
{
"name": "composer/package-versions-deprecated",
@@ -424,6 +424,72 @@
},
"time": "2022-07-20T13:12:54+00:00"
},
{
"name": "laravel/pint",
"version": "v1.2.0",
"source": {
"type": "git",
"url": "https://github.com/laravel/pint.git",
"reference": "1d276e4c803397a26cc337df908f55c2a4e90d86"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/laravel/pint/zipball/1d276e4c803397a26cc337df908f55c2a4e90d86",
"reference": "1d276e4c803397a26cc337df908f55c2a4e90d86",
"shasum": ""
},
"require": {
"ext-json": "*",
"ext-mbstring": "*",
"ext-tokenizer": "*",
"ext-xml": "*",
"php": "^8.0"
},
"require-dev": {
"friendsofphp/php-cs-fixer": "^3.11.0",
"illuminate/view": "^9.27",
"laravel-zero/framework": "^9.1.3",
"mockery/mockery": "^1.5.0",
"nunomaduro/larastan": "^2.2",
"nunomaduro/termwind": "^1.14.0",
"pestphp/pest": "^1.22.1"
},
"bin": [
"builds/pint"
],
"type": "project",
"autoload": {
"psr-4": {
"App\\": "app/",
"Database\\Seeders\\": "database/seeders/",
"Database\\Factories\\": "database/factories/"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Nuno Maduro",
"email": "enunomaduro@gmail.com"
}
],
"description": "An opinionated code formatter for PHP.",
"homepage": "https://laravel.com",
"keywords": [
"format",
"formatter",
"lint",
"linter",
"php"
],
"support": {
"issues": "https://github.com/laravel/pint/issues",
"source": "https://github.com/laravel/pint"
},
"time": "2022-09-13T15:07:15+00:00"
},
{
"name": "myclabs/deep-copy",
"version": "1.11.0",
@@ -651,17 +717,76 @@
"time": "2022-02-21T01:04:05+00:00"
},
{
"name": "phpunit/php-code-coverage",
"version": "9.2.17",
"name": "phpstan/phpstan",
"version": "1.8.11",
"source": {
"type": "git",
"url": "https://github.com/sebastianbergmann/php-code-coverage.git",
"reference": "aa94dc41e8661fe90c7316849907cba3007b10d8"
"url": "https://github.com/phpstan/phpstan.git",
"reference": "46e223dd68a620da18855c23046ddb00940b4014"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/sebastianbergmann/php-code-coverage/zipball/aa94dc41e8661fe90c7316849907cba3007b10d8",
"reference": "aa94dc41e8661fe90c7316849907cba3007b10d8",
"url": "https://api.github.com/repos/phpstan/phpstan/zipball/46e223dd68a620da18855c23046ddb00940b4014",
"reference": "46e223dd68a620da18855c23046ddb00940b4014",
"shasum": ""
},
"require": {
"php": "^7.2|^8.0"
},
"conflict": {
"phpstan/phpstan-shim": "*"
},
"bin": [
"phpstan",
"phpstan.phar"
],
"type": "library",
"autoload": {
"files": [
"bootstrap.php"
]
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"description": "PHPStan - PHP Static Analysis Tool",
"keywords": [
"dev",
"static analysis"
],
"support": {
"issues": "https://github.com/phpstan/phpstan/issues",
"source": "https://github.com/phpstan/phpstan/tree/1.8.11"
},
"funding": [
{
"url": "https://github.com/ondrejmirtes",
"type": "github"
},
{
"url": "https://github.com/phpstan",
"type": "github"
},
{
"url": "https://tidelift.com/funding/github/packagist/phpstan/phpstan",
"type": "tidelift"
}
],
"time": "2022-10-24T15:45:13+00:00"
},
{
"name": "phpunit/php-code-coverage",
"version": "9.2.18",
"source": {
"type": "git",
"url": "https://github.com/sebastianbergmann/php-code-coverage.git",
"reference": "12fddc491826940cf9b7e88ad9664cf51f0f6d0a"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/sebastianbergmann/php-code-coverage/zipball/12fddc491826940cf9b7e88ad9664cf51f0f6d0a",
"reference": "12fddc491826940cf9b7e88ad9664cf51f0f6d0a",
"shasum": ""
},
"require": {
@@ -717,7 +842,7 @@
],
"support": {
"issues": "https://github.com/sebastianbergmann/php-code-coverage/issues",
"source": "https://github.com/sebastianbergmann/php-code-coverage/tree/9.2.17"
"source": "https://github.com/sebastianbergmann/php-code-coverage/tree/9.2.18"
},
"funding": [
{
@@ -725,7 +850,7 @@
"type": "github"
}
],
"time": "2022-08-30T12:24:04+00:00"
"time": "2022-10-27T13:35:33+00:00"
},
{
"name": "phpunit/php-file-iterator",
@@ -970,16 +1095,16 @@
},
{
"name": "phpunit/phpunit",
"version": "9.5.25",
"version": "9.5.26",
"source": {
"type": "git",
"url": "https://github.com/sebastianbergmann/phpunit.git",
"reference": "3e6f90ca7e3d02025b1d147bd8d4a89fd4ca8a1d"
"reference": "851867efcbb6a1b992ec515c71cdcf20d895e9d2"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/sebastianbergmann/phpunit/zipball/3e6f90ca7e3d02025b1d147bd8d4a89fd4ca8a1d",
"reference": "3e6f90ca7e3d02025b1d147bd8d4a89fd4ca8a1d",
"url": "https://api.github.com/repos/sebastianbergmann/phpunit/zipball/851867efcbb6a1b992ec515c71cdcf20d895e9d2",
"reference": "851867efcbb6a1b992ec515c71cdcf20d895e9d2",
"shasum": ""
},
"require": {
@@ -1052,7 +1177,7 @@
],
"support": {
"issues": "https://github.com/sebastianbergmann/phpunit/issues",
"source": "https://github.com/sebastianbergmann/phpunit/tree/9.5.25"
"source": "https://github.com/sebastianbergmann/phpunit/tree/9.5.26"
},
"funding": [
{
@@ -1068,7 +1193,7 @@
"type": "tidelift"
}
],
"time": "2022-09-25T03:44:45+00:00"
"time": "2022-10-28T06:00:21+00:00"
},
{
"name": "psr/container",
@@ -2257,5 +2382,5 @@
"ext-mongodb": "*"
},
"platform-dev": [],
"plugin-api-version": "2.3.0"
"plugin-api-version": "2.2.0"
}
+1 -1
View File
@@ -14,7 +14,7 @@ services:
- "8882:8882"
mongo:
image: mongo:4.4
image: mongo:5
container_name: utopia-mongo-1
networks:
- database
+4
View File
@@ -0,0 +1,4 @@
parameters:
paths:
- src
level: 4
+3
View File
@@ -0,0 +1,3 @@
{
"preset": "psr12"
}
+15
View File
@@ -0,0 +1,15 @@
<?php
namespace Utopia\Mongo;
abstract class Adapter
{
abstract public function isConnected(): bool;
abstract public function connect(
string $host,
int $port = null,
float $timeout = null
): bool;
abstract public function send(mixed $data): int|bool;
abstract public function recv(int $timeout = null): string|bool;
}
+28
View File
@@ -0,0 +1,28 @@
<?php
namespace Utopia\Mongo\Adapter;
use Utopia\Mongo\Adapter;
class SwooleClient extends Adapter
{
public function isConnected(): bool
{
// TODO: Implement isConnected() method.
}
public function connect(string $host, int $port = null, float $timeout = null): bool
{
// TODO: Implement connect() method.
}
public function send(mixed $data): int|bool
{
// TODO: Implement send() method.
}
public function recv(int $timeout = null): string|bool
{
// TODO: Implement recv() method.
}
}
+28
View File
@@ -0,0 +1,28 @@
<?php
namespace Utopia\Mongo\Adapter;
use Utopia\Mongo\Adapter;
class SwooleCoroutineClient extends Adapter
{
public function isConnected(): bool
{
// TODO: Implement isConnected() method.
}
public function connect(string $host, int $port = null, float $timeout = null): bool
{
// TODO: Implement connect() method.
}
public function send(mixed $data): int|bool
{
// TODO: Implement send() method.
}
public function recv(int $timeout = null): string|bool
{
// TODO: Implement recv() method.
}
}
+24 -28
View File
@@ -15,14 +15,15 @@ class Auth
private string $saltedPassword;
private string $authMessage;
/**
* @throws \Exception
*/
public function __construct(array $options)
{
$this->authcid = isset($options['authcid']) ? $options['authcid'] : '';
$this->secret = isset($options['secret']) ? $options['secret'] : '';
$this->authzid = isset($options['authzid']) ? $options['authzid'] : '';
$this->service = isset($options['service']) ? $options['service'] : '';
$this->nonce = base64_encode(random_bytes(32));
$this->authcid = $options['authcid'] ?? '';
$this->secret = $options['secret'] ?? '';
$this->authzid = $options['authzid'] ?? '';
$this->cnonce = base64_encode(random_bytes(32));
}
public function start(): array
@@ -65,10 +66,10 @@ class Auth
}
/**
* @param mixed $challenge
* @return string
* @param mixed|null $challenge
* @return string|bool
*/
public function createResponse($challenge = null): string
public function createResponse(mixed $challenge = null): string|bool
{
$authcid = $this->formatName($this->authcid);
if (empty($authcid)) {
@@ -156,11 +157,11 @@ class Auth
$finalMessage = $channelBinding . ',r=' . $nonce;
$saltedPassword = $this->hi($password, $salt, $i);
$this->saltedPassword = $saltedPassword;
$clientKey = $this->hmac($saltedPassword, "Client Key", true);
$storedKey = $this->hash($clientKey, true);
$clientKey = $this->hmac($saltedPassword, "Client Key");
$storedKey = $this->hash($clientKey);
$authMessage = $this->firstMessageBare . ',' . $challenge . ',' . $finalMessage;
$this->authMessage = $authMessage;
$clientSignature = $this->hmac($storedKey, $authMessage, true);
$clientSignature = $this->hmac($storedKey, $authMessage);
$clientProof = $clientKey ^ $clientSignature;
$proof = ',p=' . base64_encode($clientProof);
@@ -178,10 +179,10 @@ class Auth
private function hi(string $str, string $salt, int $i): string
{
$int1 = "\0\0\0\1";
$ui = $this->hmac($str, $salt . $int1, true);
$ui = $this->hmac($str, $salt . $int1);
$result = $ui;
for ($k = 1; $k < $i; $k++) {
$ui = $this->hmac($str, $ui, true);
$ui = $this->hmac($str, $ui);
$result = $result ^ $ui;
}
return $result;
@@ -208,8 +209,8 @@ class Auth
$verifier = $matches[1];
$proposedServerSignature = base64_decode($verifier);
$serverKey = $this->hmac($this->saltedPassword, "Server Key", true);
$serverSignature = $this->hmac($serverKey, $this->authMessage, true);
$serverKey = $this->hmac($this->saltedPassword, "Server Key");
$serverSignature = $this->hmac($serverKey, $this->authMessage);
return $proposedServerSignature === $serverSignature;
}
@@ -239,14 +240,7 @@ class Auth
}
/**
* @return string
*/
public function getHashAlgo(): string
{
return $this->hashAlgo;
}
/**
* @param $data
* @return string
*/
private function hash($data): string
@@ -255,11 +249,13 @@ class Auth
}
/**
* @param $key
* @param $str
* @return string
*/
private function hmac($key, $str, $raw): string
private function hmac($key, $str): string
{
return hash_hmac('sha1', $str, $key, $raw);
return hash_hmac('sha1', $str, $key, true);
}
/**
@@ -285,8 +281,8 @@ class Auth
/**
* @return string
*/
static function encodeCredentials($username, $password): string
public static function encodeCredentials($username, $password): string
{
return \md5(\utf8_encode($username . ':mongo:' . $password));
}
}
}
+162 -73
View File
@@ -2,64 +2,105 @@
namespace Utopia\Mongo;
use Exception;
use MongoDB\BSON;
use Swoole\Client;
use Swoole\Client as SwooleClient;
use Swoole\Coroutine\Client as CoroutineClient;
use stdClass;
use Utopia\Mongo\Exception\Duplicate;
class MongoClient
class Client
{
/**
* Unique identifier for socket connection.
*/
private string $id;
/**
* Options for connection.
*/
private MongoClientOptions $options;
/**
* Socket (sync or async) client.
*/
private Client|CoroutineClient $client;
private SwooleClient|CoroutineClient $client;
/**
* Defines commands Mongo uses over wire protocol.
*/
public const COMMAND_CREATE = "create";
public const COMMAND_DELETE = "delete";
public const COMMAND_FIND = "find";
public const COMMAND_FIND_AND_MODIFY = "findAndModify";
public const COMMAND_GET_LAST_ERROR = "getLastError";
public const COMMAND_GET_MORE = "getMore";
public const COMMAND_INSERT = "insert";
public const COMMAND_RESET_ERROR = "resetError";
public const COMMAND_UPDATE = "update";
public const COMMAND_COUNT = "count";
public const COMMAND_AGGREGATE = "aggregate";
public const COMMAND_DISTINCT = "distinct";
public const COMMAND_MAP_REDUCE = "mapReduce";
/**
* Authentication for connection
*/
private Auth $auth;
/**
* Default Database Name
*/
private string $database;
/**
* Database $host
*/
private string $host;
/**
* Database $port
*/
private int $port;
/**
* Create a Mongo connection.
* @param MongoClientOptions $options
* @param string $database
* @param string $host
* @param int $port
* @param string $user
* @param string $password
* @param Boolean $useCoroutine
*/
public function __construct(MongoClientOptions $options, bool $useCoroutine = true)
{
public function __construct(
string $database,
string $host,
int $port,
string $user,
string $password,
bool $useCoroutine = true
) {
$this->id = uniqid('utopia.mongo.client');
$this->options = $options;
$this->database = $database;
$this->host = $host;
$this->port = $port;
$this->client = $useCoroutine
? new CoroutineClient(SWOOLE_SOCK_TCP | SWOOLE_KEEP)
: new Client(SWOOLE_SOCK_TCP | SWOOLE_KEEP);
: new SwooleClient(SWOOLE_SOCK_TCP | SWOOLE_KEEP);
$this->auth = new Auth([
'authcid' => $options->username,
'secret' => Auth::encodeCredentials($options->username, $options->password)
'authcid' => $user,
'secret' => Auth::encodeCredentials($user, $password)
]);
}
/**
* Connect to Mongo using TCP/IP
* and Wire Protocol.
* @throws Exception
*/
public function connect(): MongoClient
public function connect(): self
{
if($this->client->isConnected()) return $this;
if ($this->client->isConnected()) {
return $this;
}
$this->client->connect($this->options->host, $this->options->port);
$this->client->connect($this->host, $this->port);
[$payload, $db] = $this->auth->start();
$res = $this->query($payload, $db);
@@ -84,14 +125,15 @@ class MongoClient
/**
* Send a BSON packed query to connection.
*
* @param array $command
* @param array<string, mixed> $command
* @param string|null $db
* @return stdClass|array|int
* @throws Exception
*/
public function query(array $command, ?string $db = null): stdClass|array|int
{
$params = array_merge($command, [
'$db' => $db ?? $this->options->name,
'$db' => $db ?? $this->database,
]);
$sections = BSON\fromPHP($params);
@@ -100,7 +142,7 @@ class MongoClient
}
/**
* Send a syncronous command to connection.
* Send a synchronous command to connection.
*/
public function blocking(string $cmd): stdClass|array|int
{
@@ -130,7 +172,6 @@ class MongoClient
/**
* Receive a message from connection.
* @throws Duplicate
* @throws Exception
*/
private function receive(): stdClass|array|int
@@ -155,10 +196,18 @@ class MongoClient
(!isset($responseLength)) || ($receivedLength < $responseLength)
);
/**
* @var stdClass $result
*/
$result = BSON\toPHP(substr($res, 21, $responseLength - 21));
if (property_exists($result, "writeErrors")) {
throw new Duplicate($result->writeErrors[0]->errmsg);
// Throws a Utopia\Mongo\Exception with Code Error
throw new Exception(
$result->writeErrors[0]->errmsg,
$result->writeErrors[0]->code
);
}
if (property_exists($result, "n") && $result->ok === 1.0) {
@@ -174,7 +223,7 @@ class MongoClient
}
if ($result->ok === 1.0) {
return $result;
return $result;
}
return $result->cursor->firstBatch;
@@ -186,7 +235,7 @@ class MongoClient
* Note: Since Mongo creates on the fly, this just returns
* an instances of self.
*/
public function selectDatabase(): MongoClient
public function selectDatabase(): self
{
return $this;
}
@@ -197,7 +246,7 @@ class MongoClient
* Note: Since Mongo creates on the fly, this just returns
* an instances of self.
*/
public function createDatabase(): MongoClient
public function createDatabase(): self
{
return $this;
}
@@ -220,15 +269,16 @@ class MongoClient
* @param array $options
* @param string|null $db
* @return bool
* @throws Exception
*/
public function dropDatabase(array $options = [], ?string $db = null): bool
{
$db ??= $this->options->name;
$db ??= $this->database;
$res = $this->query(array_merge(["dropDatabase" => 1], $options), $db);
return $res->ok === 1.0;
}
public function selectCollection($name): MongoClient
public function selectCollection($name): self
{
return $this;
}
@@ -240,14 +290,14 @@ class MongoClient
* @param string $name
* @param array $options
* @return bool
* @throws Duplicate
* @throws Exception
*/
public function createCollection(string $name, array $options = []): bool
{
$list = $this->listCollectionNames(["name" => $name]);
if (\count($list->cursor->firstBatch) > 0) {
throw new Duplicate('Collection Exists');
throw new Exception('Collection Exists');
}
$res = $this->query(array_merge([
@@ -264,6 +314,7 @@ class MongoClient
* @param string $name
* @param array $options
* @return bool
* @throws Exception
*/
public function dropCollection(string $name, array $options = []): bool
{
@@ -282,10 +333,10 @@ class MongoClient
* @param array $options
*
* @return stdClass
* @throws Exception
*/
public function listCollectionNames(array $filter = [], array $options = []): stdClass
{
$qry = array_merge(
[
"listCollections" => 1.0,
@@ -308,6 +359,7 @@ class MongoClient
* @param array $options
*
* @return boolean
* @throws Exception
*/
public function createIndexes(string $collection, array $indexes, array $options = []): bool
{
@@ -341,9 +393,10 @@ class MongoClient
* @param array $indexes
* @param array $options
*
* @return array
* @return Client
* @throws Exception
*/
public function dropIndexes(string $collection, array $indexes, array $options = []): MongoClient
public function dropIndexes(string $collection, array $indexes, array $options = []): self
{
$this->query(
array_merge([
@@ -371,7 +424,9 @@ class MongoClient
$docObj = new stdClass();
foreach ($document as $key => $value) {
if(\is_null($value)) continue;
if (\is_null($value)) {
continue;
}
$docObj->{$key} = $value;
}
@@ -379,22 +434,23 @@ class MongoClient
$docObj->_id ??= new BSON\ObjectId();
$this->query(array_merge([
MongoCommand::INSERT => $collection,
self::COMMAND_INSERT => $collection,
'documents' => [$docObj],
], $options));
return $this->lastInsertedDocument($collection);
return $this->toArray($docObj);
}
/**
* Retreive the last inserted document.
* Retrieve the last lastDocument
*
* @param string $collection
*
* @return array
* @throws Exception
*/
public function lastInsertedDocument(string $collection): array
public function lastDocument(string $collection): array
{
$result = $this->find($collection, [], [
'sort' => ['_id' => -1],
@@ -413,21 +469,23 @@ class MongoClient
* @param array $updates
* @param array $options
*
* @return MongoClient
* @return Client
* @throws Exception
*/
public function update(string $collection, array $where = [], array $updates = [], array $options = []): MongoClient
public function update(string $collection, array $where = [], array $updates = [], array $options = []): self
{
$cleanUpdates = [];
foreach($updates as $k => $v) {
if(\is_null($v)) continue;
foreach ($updates as $k => $v) {
if (\is_null($v)) {
continue;
}
$cleanUpdates[$k] = $v;
}
$this->query(
array_merge([
MongoCommand::UPDATE => $collection,
self::COMMAND_UPDATE => $collection,
'updates' => [
[
'q' => $this->toObject($where),
@@ -451,15 +509,18 @@ class MongoClient
* @param array $updates
* @param array $options
*
* @return MongoClient
* @return Client
* @throws Exception
*/
public function upsert(string $collection, array $where = [], array $updates = [], array $options = []): MongoClient
public function upsert(string $collection, array $where = [], array $updates = [], array $options = []): self
{
$cleanUpdates = [];
foreach($updates as $k => $v) {
if(\is_null($v)) continue;
foreach ($updates as $k => $v) {
if (\is_null($v)) {
continue;
}
$cleanUpdates[$k] = $v;
}
@@ -491,18 +552,18 @@ class MongoClient
* @param array $options
*
* @return stdClass
* @throws Exception
*/
public function find(string $collection, array $filters = [], array $options = []): stdClass
{
$result = $this->query(
$filters = $this->cleanFilters($filters);
return $this->query(
array_merge([
MongoCommand::FIND => $collection,
self::COMMAND_FIND => $collection,
'filter' => $this->toObject($filters),
], $options)
);
return $result;
}
/**
@@ -515,20 +576,19 @@ class MongoClient
* @param array $filters
* @param array $options
*
* @return array
* @return stdClass
* @throws Exception
*/
public function findAndModify(string $collection, array $update, bool $remove = false, array $filters = [], array $options = []): stdClass
{
$result = $this->query(
return $this->query(
array_merge([
MongoCommand::FIND_AND_MODIFY => $collection,
self::COMMAND_FIND_AND_MODIFY => $collection,
'filter' => $this->toObject($filters),
'remove' => $remove,
'update' => $update,
], $options)
);
return $result;
}
/**
@@ -537,14 +597,14 @@ class MongoClient
*
* @param int $cursorId
* @param string $collection
* @param int batchSize
*
* @param int $batchSize
* @return stdClass
* @throws Exception
*/
public function getMore(int $cursorId, string $collection, int $batchSize = 25): stdClass
{
return $this->query([
MongoCommand::GET_MORE => $cursorId,
self::COMMAND_GET_MORE => $cursorId,
'collection' => $collection,
'batchSize' => $batchSize
]);
@@ -561,13 +621,14 @@ class MongoClient
* @param array $options
*
* @return int
* @throws Exception
*/
public function delete(string $collection, array $filters = [], int $limit = 1, array $deleteOptions = [], array $options = []): int
{
return $this->query(
array_merge(
[
MongoCommand::DELETE => $collection,
self::COMMAND_DELETE => $collection,
'deletes' => [
$this->toObject(
array_merge(
@@ -593,6 +654,7 @@ class MongoClient
* @param array $options
*
* @return int
* @throws Exception
*/
public function count(string $collection, array $filters, array $options): int
{
@@ -609,16 +671,15 @@ class MongoClient
* @param array $pipeline
*
* @return stdClass
* @throws Exception
*/
public function aggregate(string $collection, array $pipeline): stdClass
{
$result = $this->query([
MongoCommand::AGGREGATE => $collection,
return $this->query([
self::COMMAND_AGGREGATE => $collection,
'pipeline' => $pipeline,
'cursor' => $this->toObject([]),
]);
return $result;
}
/**
@@ -642,13 +703,14 @@ class MongoClient
/**
* Convert an object (stdClass) to an assoc array.
*
* @param stdClass|array|string|null $obj
*
* @param mixed $obj
* @return array|null
*/
public function toArray(stdClass|array|string|null $obj): array|null
public function toArray(mixed $obj): ?array
{
if(\is_null($obj)) return null;
if (\is_null($obj)) {
return null;
}
if (is_object($obj) || is_array($obj)) {
$ret = (array) $obj;
@@ -661,4 +723,31 @@ class MongoClient
return [$obj];
}
}
private function cleanFilters($filters): array
{
$cleanedFilters = [];
foreach ($filters as $k => $v) {
$value = $v;
if (in_array($k, ['$and', '$or', '$nor']) && is_array($v)) {
$values = [];
foreach ($v as $item) {
if (is_null($item)) {
continue;
}
$values[] = is_array($item) ? $this->toObject($item) : $item;
}
$value = $values;
}
$cleanedFilters[$k] = $value;
}
return $cleanedFilters;
}
}
+7
View File
@@ -0,0 +1,7 @@
<?php
namespace Utopia\Mongo;
class Exception extends \Exception
{
}
-6
View File
@@ -1,6 +0,0 @@
<?php
namespace Utopia\Mongo\Exception;
class Duplicate extends \Exception
{
}
-19
View File
@@ -1,19 +0,0 @@
<?php
namespace Utopia\Mongo;
class MongoClientOptions
{
/**
* Creates an object that contains the connection
* details for Mongo.
*/
public function __construct(
public string $name,
public string $host,
public int $port,
public string $username,
public string $password
) {
}
}
-23
View File
@@ -1,23 +0,0 @@
<?php
namespace Utopia\Mongo;
class MongoCommand
{
/**
* Defines commands Mongo uses over wire protocol.
*/
public const CREATE = "create";
public const DELETE = "delete";
public const FIND = "find";
public const FIND_AND_MODIFY = "findAndModify";
public const GET_LAST_ERROR = "getLastError";
public const GET_MORE = "getMore";
public const INSERT = "insert";
public const RESET_ERROR = "resetError";
public const UPDATE = "update";
public const COUNT = "count";
public const AGGREGATE = "aggregate";
public const DISTINCT = "distinct";
public const MAP_REDUCE = "mapReduce";
}
+24 -26
View File
@@ -4,29 +4,23 @@ namespace Utopia\Tests;
use MongoDB\BSON\ObjectId;
use PHPUnit\Framework\TestCase;
use Utopia\Mongo\Exception\Duplicate;
use Utopia\Mongo\MongoClient;
use Utopia\Mongo\MongoClientOptions;
use Utopia\Mongo\Client;
use Utopia\Mongo\Exception;
class MongoTest extends TestCase
{
static ?MongoClient $db = null;
public static ?Client $db = null;
static function getDatabase(): MongoClient
/**
* @throws Exception
*/
public static function getDatabase(): Client
{
if (!is_null(self::$db)) {
return self::$db;
}
$options = new MongoClientOptions(
'utopia_testing',
'mongo',
27017,
'root',
'example'
);
$client = new MongoClient($options, false);
$client = new Client('testing', 'mongo', 27017, 'root', 'example', false);
$client->connect();
self::$db = $client;
@@ -40,14 +34,14 @@ class MongoTest extends TestCase
/**
* @throws Duplicate
* @throws Exception
*/
public function testCreateCollection()
{
self::assertTrue($this->getDatabase()->createCollection('movies'));
self::assertTrue($this->getDatabase()->dropCollection('movies'));
self::assertTrue($this->getDatabase()->createCollection('movies'));
self::expectException(Duplicate::class);
self::expectException(Exception::class);
self::assertTrue($this->getDatabase()->createCollection('movies'));
}
@@ -58,7 +52,9 @@ class MongoTest extends TestCase
public function testCreateDocument()
{
$doc = $this->getDatabase()->insert('movies', [
$doc = $this->getDatabase()->insert(
'movies',
[
'name' => 'Armageddon',
'country' => 'USA',
'language' => 'English'
@@ -78,16 +74,19 @@ class MongoTest extends TestCase
$id = (string)$doc['_id'];
self::assertEquals(24, strlen($id));
$doc = $this->getDatabase()->insert('movies', [
$doc = $this->getDatabase()->insert(
'movies',
[
'name' => 300,
'country' => 'USA',
'language' => 'English'
]
);
$id = 999;
$doc = $this->getDatabase()->insert('movies', [
'_id' => $id,
$doc = $this->getDatabase()->insert(
'movies',
[
'_id' => 999,
'array' => ['USA', 'UK', 'India'],
'language' => 'English',
'float' => 9.9,
@@ -98,7 +97,7 @@ class MongoTest extends TestCase
]
);
$doc = $this->getDatabase()->find('movies', ['_id' => $id])->cursor->firstBatch ?? [];
$doc = $this->getDatabase()->find('movies', ['_id' => 999])->cursor->firstBatch ?? [];
$doc = $doc[0];
self::assertTrue($doc->is_open);
@@ -108,9 +107,8 @@ class MongoTest extends TestCase
self::assertIsString($doc->date_string);
self::assertIsObject($doc->date_object); // Todo: This is not working can't retrieve the object back
self::expectException(Exception::class);
self::expectExceptionCode(11000);
$this->getDatabase()->insert('movies', ['_id' => 999, 'b' => 'Duplication']);
}
}