Commit 3df57e29 authored by Mahdi Ghadamyari's avatar Mahdi Ghadamyari

Compatible with pecl-mongodb

parent a2f4eca3
<?php namespace Jenssegers\Mongodb; <?php namespace Jenssegers\Mongodb;
use Exception; use Exception;
use MongoCollection; use MongoDB\Collection as MongoCollection;
class Collection { class Collection {
...@@ -38,7 +38,6 @@ class Collection { ...@@ -38,7 +38,6 @@ class Collection {
public function __call($method, $parameters) public function __call($method, $parameters)
{ {
$start = microtime(true); $start = microtime(true);
$result = call_user_func_array([$this->collection, $method], $parameters); $result = call_user_func_array([$this->collection, $method], $parameters);
if ($this->connection->logging()) if ($this->connection->logging())
......
<?php namespace Jenssegers\Mongodb; <?php
namespace Jenssegers\Mongodb;
use MongoClient; use MongoDB;
class Connection extends \Illuminate\Database\Connection { class Connection extends \Illuminate\Database\Connection {
/** /**
...@@ -37,7 +36,7 @@ class Connection extends \Illuminate\Database\Connection { ...@@ -37,7 +36,7 @@ class Connection extends \Illuminate\Database\Connection {
$this->connection = $this->createConnection($dsn, $config, $options); $this->connection = $this->createConnection($dsn, $config, $options);
// Select database // Select database
$this->db = $this->connection->{$config['database']}; $this->db = $this->connection->selectDatabase($config['database']);
$this->useDefaultPostProcessor(); $this->useDefaultPostProcessor();
} }
...@@ -148,8 +147,7 @@ class Connection extends \Illuminate\Database\Connection { ...@@ -148,8 +147,7 @@ class Connection extends \Illuminate\Database\Connection {
{ {
$driverOptions = $config['driver_options']; $driverOptions = $config['driver_options'];
} }
return new MongoDB\Client($dsn, $options, $driverOptions);
return new MongoClient($dsn, $options, $driverOptions);
} }
/** /**
...@@ -157,7 +155,7 @@ class Connection extends \Illuminate\Database\Connection { ...@@ -157,7 +155,7 @@ class Connection extends \Illuminate\Database\Connection {
*/ */
public function disconnect() public function disconnect()
{ {
$this->connection->close(); unset($this->connection);
} }
/** /**
...@@ -193,7 +191,14 @@ class Connection extends \Illuminate\Database\Connection { ...@@ -193,7 +191,14 @@ class Connection extends \Illuminate\Database\Connection {
// The database name needs to be in the connection string, otherwise it will // The database name needs to be in the connection string, otherwise it will
// authenticate to the admin database, which may result in permission errors. // authenticate to the admin database, which may result in permission errors.
return "mongodb://" . implode(',', $hosts) . "/{$database}"; $auth = '';
if(isset($username) && $username)
$auth .= $username;
if(isset($password) && $password)
$auth .= ':'.$password;
if($auth)
$auth .= '@';
return "mongodb://" . $auth . implode(',', $hosts) . "/{$database}";
} }
/** /**
......
...@@ -10,10 +10,8 @@ use Jenssegers\Mongodb\Query\Builder as QueryBuilder; ...@@ -10,10 +10,8 @@ use Jenssegers\Mongodb\Query\Builder as QueryBuilder;
use Jenssegers\Mongodb\Relations\EmbedsMany; use Jenssegers\Mongodb\Relations\EmbedsMany;
use Jenssegers\Mongodb\Relations\EmbedsOne; use Jenssegers\Mongodb\Relations\EmbedsOne;
use Jenssegers\Mongodb\Relations\EmbedsOneOrMany; use Jenssegers\Mongodb\Relations\EmbedsOneOrMany;
use MongoDate;
use MongoId;
use ReflectionMethod; use ReflectionMethod;
use MongoDB;
abstract class Model extends BaseModel { abstract class Model extends BaseModel {
use HybridRelations; use HybridRelations;
...@@ -54,8 +52,8 @@ abstract class Model extends BaseModel { ...@@ -54,8 +52,8 @@ abstract class Model extends BaseModel {
$value = $this->attributes['_id']; $value = $this->attributes['_id'];
} }
// Convert MongoId's to string. // Convert MongoDB\BSON\ObjectID's to string.
if ($value instanceof MongoId) if ($value instanceof MongoDB\BSON\ObjectID)
{ {
return (string) $value; return (string) $value;
} }
...@@ -150,15 +148,15 @@ abstract class Model extends BaseModel { ...@@ -150,15 +148,15 @@ abstract class Model extends BaseModel {
} }
/** /**
* Convert a DateTime to a storable MongoDate object. * Convert a DateTime to a storable MongoDB\BSON\UTCDateTime object.
* *
* @param DateTime|int $value * @param DateTime|int $value
* @return MongoDate * @return MongoDB\BSON\UTCDateTime
*/ */
public function fromDateTime($value) public function fromDateTime($value)
{ {
// If the value is already a MongoDate instance, we don't need to parse it. // If the value is already a MongoDB\BSON\UTCDateTime instance, we don't need to parse it.
if ($value instanceof MongoDate) if ($value instanceof MongoDB\BSON\UTCDateTime)
{ {
return $value; return $value;
} }
...@@ -169,7 +167,8 @@ abstract class Model extends BaseModel { ...@@ -169,7 +167,8 @@ abstract class Model extends BaseModel {
$value = parent::asDateTime($value); $value = parent::asDateTime($value);
} }
return new MongoDate($value->getTimestamp());
return new MongoDB\BSON\UTCDateTime($value->getTimestamp());
} }
/** /**
...@@ -180,8 +179,8 @@ abstract class Model extends BaseModel { ...@@ -180,8 +179,8 @@ abstract class Model extends BaseModel {
*/ */
protected function asDateTime($value) protected function asDateTime($value)
{ {
// Convert MongoDate instances. // Convert MongoDB\BSON\UTCDateTime instances.
if ($value instanceof MongoDate) if ($value instanceof MongoDB\BSON\UTCDateTime)
{ {
return Carbon::createFromTimestamp($value->sec); return Carbon::createFromTimestamp($value->sec);
} }
...@@ -202,11 +201,11 @@ abstract class Model extends BaseModel { ...@@ -202,11 +201,11 @@ abstract class Model extends BaseModel {
/** /**
* Get a fresh timestamp for the model. * Get a fresh timestamp for the model.
* *
* @return MongoDate * @return MongoDB\BSON\UTCDateTime
*/ */
public function freshTimestamp() public function freshTimestamp()
{ {
return new MongoDate; return round(microtime(true) * 1000);
} }
/** /**
...@@ -298,7 +297,7 @@ abstract class Model extends BaseModel { ...@@ -298,7 +297,7 @@ abstract class Model extends BaseModel {
*/ */
public function setAttribute($key, $value) public function setAttribute($key, $value)
{ {
// Convert _id to MongoId. // Convert _id to MongoDB\BSON\ObjectID.
if ($key == '_id' and is_string($value)) if ($key == '_id' and is_string($value))
{ {
$builder = $this->newBaseQueryBuilder(); $builder = $this->newBaseQueryBuilder();
...@@ -337,7 +336,7 @@ abstract class Model extends BaseModel { ...@@ -337,7 +336,7 @@ abstract class Model extends BaseModel {
// nicely when your models are converted to JSON. // nicely when your models are converted to JSON.
foreach ($attributes as $key => &$value) foreach ($attributes as $key => &$value)
{ {
if ($value instanceof MongoId) if ($value instanceof MongoDB\BSON\ObjectID)
{ {
$value = (string) $value; $value = (string) $value;
} }
...@@ -355,29 +354,6 @@ abstract class Model extends BaseModel { ...@@ -355,29 +354,6 @@ abstract class Model extends BaseModel {
return $attributes; return $attributes;
} }
/**
* Determine if the new and old values for a given key are numerically equivalent.
*
* @param string $key
* @return bool
*/
protected function originalIsNumericallyEquivalent($key)
{
$current = $this->attributes[$key];
$original = $this->original[$key];
// Date comparison.
if (in_array($key, $this->getDates()))
{
$current = $current instanceof MongoDate ? $this->asDateTime($current) : $current;
$original = $original instanceof MongoDate ? $this->asDateTime($original) : $original;
return $current == $original;
}
return parent::originalIsNumericallyEquivalent($key);
}
/** /**
* Remove one or more fields. * Remove one or more fields.
* *
......
...@@ -7,9 +7,7 @@ use Illuminate\Database\Query\Expression; ...@@ -7,9 +7,7 @@ use Illuminate\Database\Query\Expression;
use Illuminate\Support\Arr; use Illuminate\Support\Arr;
use Illuminate\Support\Collection; use Illuminate\Support\Collection;
use Jenssegers\Mongodb\Connection; use Jenssegers\Mongodb\Connection;
use MongoDate; use MongoDB;
use MongoId;
use MongoRegex;
class Builder extends BaseBuilder { class Builder extends BaseBuilder {
...@@ -245,10 +243,10 @@ class Builder extends BaseBuilder { ...@@ -245,10 +243,10 @@ class Builder extends BaseBuilder {
if ($this->projections) $pipeline[] = ['$project' => $this->projections]; if ($this->projections) $pipeline[] = ['$project' => $this->projections];
// Execute aggregation // Execute aggregation
$results = $this->collection->aggregate($pipeline); $results = $this->collection->aggregate($pipeline, ['useCursor'=>false]);
// Return results // Return results
return $results['result']; return $results;
} }
// Distinct query // Distinct query
...@@ -286,17 +284,18 @@ class Builder extends BaseBuilder { ...@@ -286,17 +284,18 @@ class Builder extends BaseBuilder {
{ {
$columns = array_merge($columns, $this->projections); $columns = array_merge($columns, $this->projections);
} }
$options = [];
// Execute query and get MongoCursor
$cursor = $this->collection->find($wheres, $columns);
// Apply order, offset, limit and hint // Apply order, offset, limit and hint
if ($this->timeout) $cursor->timeout($this->timeout); if ($this->timeout) $options['maxTimeMS'] = $this->timeout;
if ($this->orders) $cursor->sort($this->orders); if ($this->orders) $options['sort'] = $this->orders;
if ($this->offset) $cursor->skip($this->offset); if ($this->offset) $options['skip'] = $this->offset;
if ($this->limit) $cursor->limit($this->limit); if ($this->limit) $options['limit'] = $this->limit;
if ($this->hint) $cursor->hint($this->hint); if ($this->hint) $cursor->hint($this->hint);
// Execute query and get MongoCursor
$cursor = $this->collection->find($wheres, $options);
// Return results as an array with numeric keys // Return results as an array with numeric keys
return iterator_to_array($cursor, false); return iterator_to_array($cursor, false);
} }
...@@ -310,8 +309,8 @@ class Builder extends BaseBuilder { ...@@ -310,8 +309,8 @@ class Builder extends BaseBuilder {
public function generateCacheKey() public function generateCacheKey()
{ {
$key = [ $key = [
'connection' => $this->connection->getName(), 'connection' => $this->collection->getDatabaseName(),
'collection' => $this->collection->getName(), 'collection' => $this->collection->getCollectionName(),
'wheres' => $this->wheres, 'wheres' => $this->wheres,
'columns' => $this->columns, 'columns' => $this->columns,
'groups' => $this->groups, 'groups' => $this->groups,
...@@ -460,9 +459,9 @@ class Builder extends BaseBuilder { ...@@ -460,9 +459,9 @@ class Builder extends BaseBuilder {
if ( ! $batch) $values = [$values]; if ( ! $batch) $values = [$values];
// Batch insert // Batch insert
$result = $this->collection->batchInsert($values); $result = $this->collection->InsertMany($values);
return (1 == (int) $result['ok']); return (1 == (int) $result->isAcknowledged());
} }
/** /**
...@@ -474,9 +473,8 @@ class Builder extends BaseBuilder { ...@@ -474,9 +473,8 @@ class Builder extends BaseBuilder {
*/ */
public function insertGetId(array $values, $sequence = null) public function insertGetId(array $values, $sequence = null)
{ {
$result = $this->collection->insert($values); $result = $this->collection->InsertOne($values);
if (1 == (int) $result->isAcknowledged())
if (1 == (int) $result['ok'])
{ {
if (is_null($sequence)) if (is_null($sequence))
{ {
...@@ -484,7 +482,7 @@ class Builder extends BaseBuilder { ...@@ -484,7 +482,7 @@ class Builder extends BaseBuilder {
} }
// Return id // Return id
return $values[$sequence]; return $sequence == '_id' ? $result->getInsertedId()->__toString() : $values[$sequence];
} }
} }
...@@ -577,12 +575,10 @@ class Builder extends BaseBuilder { ...@@ -577,12 +575,10 @@ class Builder extends BaseBuilder {
public function delete($id = null) public function delete($id = null)
{ {
$wheres = $this->compileWheres(); $wheres = $this->compileWheres();
$result = $this->collection->DeleteMany($wheres);
$result = $this->collection->remove($wheres); if (1 == (int) $result->isAcknowledged())
if (1 == (int) $result['ok'])
{ {
return $result['n']; return $result->getDeletedCount();
} }
return 0; return 0;
...@@ -609,9 +605,8 @@ class Builder extends BaseBuilder { ...@@ -609,9 +605,8 @@ class Builder extends BaseBuilder {
*/ */
public function truncate() public function truncate()
{ {
$result = $this->collection->remove(); $result = $this->collection->drop();
return (1 == (int) $result->ok);
return (1 == (int) $result['ok']);
} }
/** /**
...@@ -627,7 +622,7 @@ class Builder extends BaseBuilder { ...@@ -627,7 +622,7 @@ class Builder extends BaseBuilder {
{ {
$results = new Collection($this->get([$column, $key])); $results = new Collection($this->get([$column, $key]));
// Convert MongoId's to strings so that lists can do its work. // Convert MongoDB\BSON\ObjectID's to strings so that lists can do its work.
$results = $results->map(function ($item) $results = $results->map(function ($item)
{ {
$item['_id'] = (string) $item['_id']; $item['_id'] = (string) $item['_id'];
...@@ -771,30 +766,28 @@ class Builder extends BaseBuilder { ...@@ -771,30 +766,28 @@ class Builder extends BaseBuilder {
} }
$wheres = $this->compileWheres(); $wheres = $this->compileWheres();
$result = $this->collection->UpdateMany($wheres, $query, $options);
$result = $this->collection->update($wheres, $query, $options); if (1 == (int) $result->isAcknowledged())
if (1 == (int) $result['ok'])
{ {
return $result['n']; return $result->getModifiedCount() ? $result->getModifiedCount() : $result->getUpsertedCount();
} }
return 0; return 0;
} }
/** /**
* Convert a key to MongoID if needed. * Convert a key to MongoDB\BSON\ObjectID if needed.
* *
* @param mixed $id * @param mixed $id
* @return mixed * @return mixed
*/ */
public function convertKey($id) public function convertKey($id)
{ {
if (MongoId::isValid($id)) try {
{ $id = new MongoDB\BSON\ObjectID($id);
return new MongoId($id); } catch (MongoDB\Driver\Exception\InvalidArgumentException $e) {
return false;
} }
return $id; return $id;
} }
...@@ -884,10 +877,10 @@ class Builder extends BaseBuilder { ...@@ -884,10 +877,10 @@ class Builder extends BaseBuilder {
} }
} }
// Convert DateTime values to MongoDate. // Convert DateTime values to MongoDB\BSON\UTCDateTime.
if (isset($where['value']) and $where['value'] instanceof DateTime) if (isset($where['value']) and $where['value'] instanceof DateTime)
{ {
$where['value'] = new MongoDate($where['value']->getTimestamp()); $where['value'] = new MongoDB\BSON\UTCDateTime($where['value']->getTimestamp());
} }
// The next item in a "chain" of wheres devices the boolean of the // The next item in a "chain" of wheres devices the boolean of the
...@@ -926,7 +919,7 @@ class Builder extends BaseBuilder { ...@@ -926,7 +919,7 @@ class Builder extends BaseBuilder {
{ {
extract($where); extract($where);
// Replace like with a MongoRegex instance. // Replace like with a MongoDB\BSON\Regex instance.
if ($operator == 'like') if ($operator == 'like')
{ {
$operator = '='; $operator = '=';
...@@ -936,20 +929,23 @@ class Builder extends BaseBuilder { ...@@ -936,20 +929,23 @@ class Builder extends BaseBuilder {
if ( ! starts_with($value, '%')) $regex = '^' . $regex; if ( ! starts_with($value, '%')) $regex = '^' . $regex;
if ( ! ends_with($value, '%')) $regex = $regex . '$'; if ( ! ends_with($value, '%')) $regex = $regex . '$';
$value = new MongoRegex("/$regex/i"); $value = new MongoDB\BSON\Regex($regex, 'i');
} }
// Manipulate regexp operations. // Manipulate regexp operations.
elseif (in_array($operator, ['regexp', 'not regexp', 'regex', 'not regex'])) elseif (in_array($operator, ['regexp', 'not regexp', 'regex', 'not regex']))
{ {
// Automatically convert regular expression strings to MongoRegex objects. // Automatically convert regular expression strings to MongoDB\BSON\Regex objects.
if ( ! $value instanceof MongoRegex) if ( ! $value instanceof MongoDB\BSON\Regex)
{ {
$value = new MongoRegex($value); $e = explode('/', $value);
$flag = end($e);
$regstr = substr($value, 1, -(strlen($flag)+1));
$value = new MongoDB\BSON\Regex($regstr, $flag);
} }
// For inverse regexp operations, we can just use the $not operator // For inverse regexp operations, we can just use the $not operator
// and pass it a MongoRegex instence. // and pass it a MongoDB\BSON\Regex instence.
if (starts_with($operator, 'not')) if (starts_with($operator, 'not'))
{ {
$operator = 'not'; $operator = 'not';
...@@ -968,7 +964,6 @@ class Builder extends BaseBuilder { ...@@ -968,7 +964,6 @@ class Builder extends BaseBuilder {
{ {
$query = [$column => ['$' . $operator => $value]]; $query = [$column => ['$' . $operator => $value]];
} }
return $query; return $query;
} }
......
...@@ -126,9 +126,7 @@ class BelongsToMany extends EloquentBelongsToMany { ...@@ -126,9 +126,7 @@ class BelongsToMany extends EloquentBelongsToMany {
{ {
$this->detach($detach); $this->detach($detach);
$changes['detached'] = (array) array_map(function ($v) { $changes['detached'] = (array) array_map(function ($v) { return (int) $v; }, $detach);
return is_numeric($v) ? (int) $v : (string) $v;
}, $detach);
} }
// Now we are finally ready to attach the new records. Note that we'll disable // Now we are finally ready to attach the new records. Note that we'll disable
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment