Commit eeb6f266 authored by Giacomo Fabbian's avatar Giacomo Fabbian

Merge branch 'master' into add_test_for_negative_dates

parents 64089649 3d58b4b3
github: jenssegers github: jenssegers
open_collective: laravel-mongodb tidelift: "packagist/jenssegers/mongodb"
MIT License
Copyright (c) 2020 Jens Segers
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
...@@ -63,7 +63,7 @@ Make sure you have the MongoDB PHP driver installed. You can find installation i ...@@ -63,7 +63,7 @@ Make sure you have the MongoDB PHP driver installed. You can find installation i
5.6.x | 3.4.x 5.6.x | 3.4.x
5.7.x | 3.4.x 5.7.x | 3.4.x
5.8.x | 3.5.x 5.8.x | 3.5.x
6.0.x | 3.6.x 6.x | 3.6.x
Install the package via Composer: Install the package via Composer:
...@@ -751,7 +751,7 @@ The belongsToMany relation will not use a pivot "table" but will push id's to a ...@@ -751,7 +751,7 @@ The belongsToMany relation will not use a pivot "table" but will push id's to a
If you want to define custom keys for your relation, set it to `null`: If you want to define custom keys for your relation, set it to `null`:
```php ```php
use Jenssegers\Mongodb\Eloquent\Mode; use Jenssegers\Mongodb\Eloquent\Model;
class User extends Model class User extends Model
{ {
...@@ -1134,3 +1134,7 @@ Embedded relations now return an `Illuminate\Database\Eloquent\Collection` rathe ...@@ -1134,3 +1134,7 @@ Embedded relations now return an `Illuminate\Database\Eloquent\Collection` rathe
```php ```php
$books = $user->books()->sortBy('title')->get(); $books = $user->books()->sortBy('title')->get();
``` ```
## Security contact information
To report a security vulnerability, follow [these steps](https://tidelift.com/security).
...@@ -5,6 +5,7 @@ namespace Jenssegers\Mongodb\Auth; ...@@ -5,6 +5,7 @@ namespace Jenssegers\Mongodb\Auth;
use DateTime; use DateTime;
use DateTimeZone; use DateTimeZone;
use Illuminate\Auth\Passwords\DatabaseTokenRepository as BaseDatabaseTokenRepository; use Illuminate\Auth\Passwords\DatabaseTokenRepository as BaseDatabaseTokenRepository;
use Illuminate\Support\Facades\Date;
use MongoDB\BSON\UTCDateTime; use MongoDB\BSON\UTCDateTime;
class DatabaseTokenRepository extends BaseDatabaseTokenRepository class DatabaseTokenRepository extends BaseDatabaseTokenRepository
...@@ -17,7 +18,7 @@ class DatabaseTokenRepository extends BaseDatabaseTokenRepository ...@@ -17,7 +18,7 @@ class DatabaseTokenRepository extends BaseDatabaseTokenRepository
return [ return [
'email' => $email, 'email' => $email,
'token' => $this->hasher->make($token), 'token' => $this->hasher->make($token),
'created_at' => new UTCDateTime(time() * 1000), 'created_at' => new UTCDateTime(Date::now()->format('Uv')),
]; ];
} }
...@@ -37,7 +38,7 @@ class DatabaseTokenRepository extends BaseDatabaseTokenRepository ...@@ -37,7 +38,7 @@ class DatabaseTokenRepository extends BaseDatabaseTokenRepository
protected function tokenRecentlyCreated($createdAt) protected function tokenRecentlyCreated($createdAt)
{ {
$createdAt = $this->convertDateTime($createdAt); $createdAt = $this->convertDateTime($createdAt);
return parent::tokenRecentlyCreated($createdAt); return parent::tokenRecentlyCreated($createdAt);
} }
......
...@@ -4,6 +4,7 @@ namespace Jenssegers\Mongodb; ...@@ -4,6 +4,7 @@ namespace Jenssegers\Mongodb;
use Illuminate\Database\Connection as BaseConnection; use Illuminate\Database\Connection as BaseConnection;
use Illuminate\Support\Arr; use Illuminate\Support\Arr;
use InvalidArgumentException;
use MongoDB\Client; use MongoDB\Client;
class Connection extends BaseConnection class Connection extends BaseConnection
...@@ -37,8 +38,11 @@ class Connection extends BaseConnection ...@@ -37,8 +38,11 @@ class Connection extends BaseConnection
// Create the connection // Create the connection
$this->connection = $this->createConnection($dsn, $config, $options); $this->connection = $this->createConnection($dsn, $config, $options);
// Get default database name
$default_db = $this->getDefaultDatabaseName($dsn, $config);
// Select database // Select database
$this->db = $this->connection->selectDatabase($this->getDatabaseDsn($dsn, $config['database'])); $this->db = $this->connection->selectDatabase($default_db);
$this->useDefaultPostProcessor(); $this->useDefaultPostProcessor();
...@@ -114,6 +118,26 @@ class Connection extends BaseConnection ...@@ -114,6 +118,26 @@ class Connection extends BaseConnection
return $this->getMongoDB()->getDatabaseName(); return $this->getMongoDB()->getDatabaseName();
} }
/**
* Get the name of the default database based on db config or try to detect it from dsn
* @param string $dsn
* @param array $config
* @return string
* @throws InvalidArgumentException
*/
protected function getDefaultDatabaseName($dsn, $config)
{
if (empty($config['database'])) {
if (preg_match('/^mongodb(?:[+]srv)?:\\/\\/.+\\/([^?&]+)/s', $dsn, $matches)) {
$config['database'] = $matches[1];
} else {
throw new InvalidArgumentException("Database is not properly configured.");
}
}
return $config['database'];
}
/** /**
* Create a new MongoDB connection. * Create a new MongoDB connection.
* @param string $dsn * @param string $dsn
...@@ -191,18 +215,6 @@ class Connection extends BaseConnection ...@@ -191,18 +215,6 @@ class Connection extends BaseConnection
return 'mongodb://' . implode(',', $hosts) . ($auth_database ? '/' . $auth_database : ''); return 'mongodb://' . implode(',', $hosts) . ($auth_database ? '/' . $auth_database : '');
} }
/**
* Get database name from DSN string, if there is no database in DSN path - returns back $database argument.
* @param string $dsn
* @param $database
* @return string
*/
protected function getDatabaseDsn($dsn, $database)
{
$dsnDatabase = trim(parse_url($dsn, PHP_URL_PATH), '/');
return trim($dsnDatabase) ? $dsnDatabase : $database;
}
/** /**
* Create a DSN string from a configuration. * Create a DSN string from a configuration.
* @param array $config * @param array $config
......
...@@ -2,13 +2,13 @@ ...@@ -2,13 +2,13 @@
namespace Jenssegers\Mongodb\Eloquent; namespace Jenssegers\Mongodb\Eloquent;
use Illuminate\Support\Carbon;
use DateTime; use DateTime;
use Illuminate\Contracts\Queue\QueueableCollection; use Illuminate\Contracts\Queue\QueueableCollection;
use Illuminate\Contracts\Queue\QueueableEntity; use Illuminate\Contracts\Queue\QueueableEntity;
use Illuminate\Database\Eloquent\Model as BaseModel; use Illuminate\Database\Eloquent\Model as BaseModel;
use Illuminate\Database\Eloquent\Relations\Relation; use Illuminate\Database\Eloquent\Relations\Relation;
use Illuminate\Support\Arr; use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Date;
use Illuminate\Support\Str; use Illuminate\Support\Str;
use Jenssegers\Mongodb\Query\Builder as QueryBuilder; use Jenssegers\Mongodb\Query\Builder as QueryBuilder;
use MongoDB\BSON\Binary; use MongoDB\BSON\Binary;
...@@ -89,7 +89,7 @@ abstract class Model extends BaseModel ...@@ -89,7 +89,7 @@ abstract class Model extends BaseModel
$value = parent::asDateTime($value); $value = parent::asDateTime($value);
} }
return new UTCDateTime($value->getTimestamp() * 1000); return new UTCDateTime($value->format('Uv'));
} }
/** /**
...@@ -99,7 +99,7 @@ abstract class Model extends BaseModel ...@@ -99,7 +99,7 @@ abstract class Model extends BaseModel
{ {
// Convert UTCDateTime instances. // Convert UTCDateTime instances.
if ($value instanceof UTCDateTime) { if ($value instanceof UTCDateTime) {
return Carbon::createFromTimestamp($value->toDateTime()->getTimestamp()); return Date::createFromTimestampMs($value->toDateTime()->format('Uv'));
} }
return parent::asDateTime($value); return parent::asDateTime($value);
...@@ -118,7 +118,7 @@ abstract class Model extends BaseModel ...@@ -118,7 +118,7 @@ abstract class Model extends BaseModel
*/ */
public function freshTimestamp() public function freshTimestamp()
{ {
return new UTCDateTime(Carbon::now()); return new UTCDateTime(Date::now()->format('Uv'));
} }
/** /**
......
...@@ -2,7 +2,7 @@ ...@@ -2,7 +2,7 @@
namespace Jenssegers\Mongodb; namespace Jenssegers\Mongodb;
use DB; use Illuminate\Support\Facades\DB;
use Illuminate\Queue\QueueServiceProvider; use Illuminate\Queue\QueueServiceProvider;
use Jenssegers\Mongodb\Queue\Failed\MongoFailedJobProvider; use Jenssegers\Mongodb\Queue\Failed\MongoFailedJobProvider;
......
...@@ -8,6 +8,7 @@ use Illuminate\Database\Query\Builder as BaseBuilder; ...@@ -8,6 +8,7 @@ use Illuminate\Database\Query\Builder as BaseBuilder;
use Illuminate\Database\Query\Expression; use Illuminate\Database\Query\Expression;
use Illuminate\Support\Arr; use Illuminate\Support\Arr;
use Illuminate\Support\Collection; use Illuminate\Support\Collection;
use Illuminate\Support\LazyCollection;
use Illuminate\Support\Str; use Illuminate\Support\Str;
use Jenssegers\Mongodb\Connection; use Jenssegers\Mongodb\Connection;
use MongoCollection; use MongoCollection;
...@@ -15,7 +16,12 @@ use MongoDB\BSON\Binary; ...@@ -15,7 +16,12 @@ use MongoDB\BSON\Binary;
use MongoDB\BSON\ObjectID; use MongoDB\BSON\ObjectID;
use MongoDB\BSON\Regex; use MongoDB\BSON\Regex;
use MongoDB\BSON\UTCDateTime; use MongoDB\BSON\UTCDateTime;
use RuntimeException;
/**
* Class Builder
* @package Jenssegers\Mongodb\Query
*/
class Builder extends BaseBuilder class Builder extends BaseBuilder
{ {
/** /**
...@@ -209,12 +215,25 @@ class Builder extends BaseBuilder ...@@ -209,12 +215,25 @@ class Builder extends BaseBuilder
return $this->getFresh($columns); return $this->getFresh($columns);
} }
/**
* @inheritdoc
*/
public function cursor($columns = [])
{
$result = $this->getFresh($columns, true);
if ($result instanceof LazyCollection) {
return $result;
}
throw new RuntimeException("Query not compatible with cursor");
}
/** /**
* Execute the query as a fresh "select" statement. * Execute the query as a fresh "select" statement.
* @param array $columns * @param array $columns
* @return array|static[]|Collection * @param bool $returnLazy
* @return array|static[]|Collection|LazyCollection
*/ */
public function getFresh($columns = []) public function getFresh($columns = [], $returnLazy = false)
{ {
// If no columns have been specified for the select statement, we will set them // If no columns have been specified for the select statement, we will set them
// here to either the passed columns, or the standard default of retrieving // here to either the passed columns, or the standard default of retrieving
...@@ -294,7 +313,7 @@ class Builder extends BaseBuilder ...@@ -294,7 +313,7 @@ class Builder extends BaseBuilder
} }
} }
} }
// The _id field is mandatory when using grouping. // The _id field is mandatory when using grouping.
if ($group && empty($group['_id'])) { if ($group && empty($group['_id'])) {
$group['_id'] = null; $group['_id'] = null;
...@@ -402,6 +421,14 @@ class Builder extends BaseBuilder ...@@ -402,6 +421,14 @@ class Builder extends BaseBuilder
// Execute query and get MongoCursor // Execute query and get MongoCursor
$cursor = $this->collection->find($wheres, $options); $cursor = $this->collection->find($wheres, $options);
if ($returnLazy) {
return LazyCollection::make(function () use ($cursor) {
foreach ($cursor as $item) {
yield $item;
}
});
}
// Return results as an array with numeric keys // Return results as an array with numeric keys
$results = iterator_to_array($cursor, false); $results = iterator_to_array($cursor, false);
return $this->useCollections ? new Collection($results) : $results; return $this->useCollections ? new Collection($results) : $results;
...@@ -930,18 +957,18 @@ class Builder extends BaseBuilder ...@@ -930,18 +957,18 @@ class Builder extends BaseBuilder
if (is_array($where['value'])) { if (is_array($where['value'])) {
array_walk_recursive($where['value'], function (&$item, $key) { array_walk_recursive($where['value'], function (&$item, $key) {
if ($item instanceof DateTime) { if ($item instanceof DateTime) {
$item = new UTCDateTime($item->getTimestamp() * 1000); $item = new UTCDateTime($item->format('Uv'));
} }
}); });
} else { } else {
if ($where['value'] instanceof DateTime) { if ($where['value'] instanceof DateTime) {
$where['value'] = new UTCDateTime($where['value']->getTimestamp() * 1000); $where['value'] = new UTCDateTime($where['value']->format('Uv'));
} }
} }
} elseif (isset($where['values'])) { } elseif (isset($where['values'])) {
array_walk_recursive($where['values'], function (&$item, $key) { array_walk_recursive($where['values'], function (&$item, $key) {
if ($item instanceof DateTime) { if ($item instanceof DateTime) {
$item = new UTCDateTime($item->getTimestamp() * 1000); $item = new UTCDateTime($item->format('Uv'));
} }
}); });
} }
...@@ -993,6 +1020,7 @@ class Builder extends BaseBuilder ...@@ -993,6 +1020,7 @@ class Builder extends BaseBuilder
protected function compileWhereBasic(array $where) protected function compileWhereBasic(array $where)
{ {
extract($where); extract($where);
$is_numeric = false;
// Replace like or not like with a Regex instance. // Replace like or not like with a Regex instance.
if (in_array($operator, ['like', 'not like'])) { if (in_array($operator, ['like', 'not like'])) {
...@@ -1004,15 +1032,21 @@ class Builder extends BaseBuilder ...@@ -1004,15 +1032,21 @@ class Builder extends BaseBuilder
// Convert to regular expression. // Convert to regular expression.
$regex = preg_replace('#(^|[^\\\])%#', '$1.*', preg_quote($value)); $regex = preg_replace('#(^|[^\\\])%#', '$1.*', preg_quote($value));
$plain_value = $value;
// Convert like to regular expression. // Convert like to regular expression.
if (!Str::startsWith($value, '%')) { if (!Str::startsWith($value, '%')) {
$regex = '^' . $regex; $regex = '^' . $regex;
} else {
$plain_value = Str::replaceFirst('%', null, $plain_value);
} }
if (!Str::endsWith($value, '%')) { if (!Str::endsWith($value, '%')) {
$regex .= '$'; $regex .= '$';
} else {
$plain_value = Str::replaceLast('%', null, $plain_value);
} }
$is_numeric = is_numeric($plain_value);
$value = new Regex($regex, 'i'); $value = new 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'])) {
...@@ -1032,7 +1066,11 @@ class Builder extends BaseBuilder ...@@ -1032,7 +1066,11 @@ class Builder extends BaseBuilder
} }
if (!isset($operator) || $operator == '=') { if (!isset($operator) || $operator == '=') {
$query = [$column => $value]; if ($is_numeric) {
$query = ['$where' => '/^'.$value->getPattern().'/.test(this.'.$column.')'];
} else {
$query = [$column => $value];
}
} elseif (array_key_exists($operator, $this->conversion)) { } elseif (array_key_exists($operator, $this->conversion)) {
$query = [$column => [$this->conversion[$operator] => $value]]; $query = [$column => [$this->conversion[$operator] => $value]];
} else { } else {
......
...@@ -12,12 +12,15 @@ class MongoFailedJobProvider extends DatabaseFailedJobProvider ...@@ -12,12 +12,15 @@ class MongoFailedJobProvider extends DatabaseFailedJobProvider
* @param string $connection * @param string $connection
* @param string $queue * @param string $queue
* @param string $payload * @param string $payload
* @param \Exception $exception
* @return void * @return void
*/ */
public function log($connection, $queue, $payload, $exception) public function log($connection, $queue, $payload, $exception)
{ {
$failed_at = Carbon::now()->getTimestamp(); $failed_at = Carbon::now()->getTimestamp();
$exception = (string) $exception;
$this->getTable()->insert(compact('connection', 'queue', 'payload', 'failed_at', 'exception')); $this->getTable()->insert(compact('connection', 'queue', 'payload', 'failed_at', 'exception'));
} }
......
...@@ -265,7 +265,7 @@ class BelongsToMany extends EloquentBelongsToMany ...@@ -265,7 +265,7 @@ class BelongsToMany extends EloquentBelongsToMany
/** /**
* @inheritdoc * @inheritdoc
*/ */
protected function newPivotQuery() public function newPivotQuery()
{ {
return $this->newRelatedQuery(); return $this->newRelatedQuery();
} }
......
...@@ -8,9 +8,6 @@ use MongoDB\BSON\ObjectID; ...@@ -8,9 +8,6 @@ use MongoDB\BSON\ObjectID;
class EmbedsOne extends EmbedsOneOrMany class EmbedsOne extends EmbedsOneOrMany
{ {
/**
* @inheritdoc
*/
public function initRelation(array $models, $relation) public function initRelation(array $models, $relation)
{ {
foreach ($models as $model) { foreach ($models as $model) {
...@@ -20,14 +17,19 @@ class EmbedsOne extends EmbedsOneOrMany ...@@ -20,14 +17,19 @@ class EmbedsOne extends EmbedsOneOrMany
return $models; return $models;
} }
/**
* @inheritdoc
*/
public function getResults() public function getResults()
{ {
return $this->toModel($this->getEmbedded()); return $this->toModel($this->getEmbedded());
} }
public function getEager()
{
$eager = $this->get();
// EmbedsOne only brings one result, Eager needs a collection!
return $this->toCollection([$eager]);
}
/** /**
* Save a new model and attach it to the parent model. * Save a new model and attach it to the parent model.
* @param Model $model * @param Model $model
......
...@@ -15,7 +15,7 @@ class AuthTest extends TestCase ...@@ -15,7 +15,7 @@ class AuthTest extends TestCase
public function testAuthAttempt() public function testAuthAttempt()
{ {
$user = User::create([ User::create([
'name' => 'John Doe', 'name' => 'John Doe',
'email' => 'john@doe.com', 'email' => 'john@doe.com',
'password' => Hash::make('foobar'), 'password' => Hash::make('foobar'),
......
...@@ -2,13 +2,19 @@ ...@@ -2,13 +2,19 @@
declare(strict_types=1); declare(strict_types=1);
use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\DB;
use Jenssegers\Mongodb\Collection;
use Jenssegers\Mongodb\Connection;
use Jenssegers\Mongodb\Query\Builder;
use Jenssegers\Mongodb\Schema\Builder as SchemaBuilder;
use MongoDB\Client;
use MongoDB\Database;
class ConnectionTest extends TestCase class ConnectionTest extends TestCase
{ {
public function testConnection() public function testConnection()
{ {
$connection = DB::connection('mongodb'); $connection = DB::connection('mongodb');
$this->assertInstanceOf(\Jenssegers\Mongodb\Connection::class, $connection); $this->assertInstanceOf(Connection::class, $connection);
} }
public function testReconnect() public function testReconnect()
...@@ -26,45 +32,29 @@ class ConnectionTest extends TestCase ...@@ -26,45 +32,29 @@ class ConnectionTest extends TestCase
public function testDb() public function testDb()
{ {
$connection = DB::connection('mongodb'); $connection = DB::connection('mongodb');
$this->assertInstanceOf(\MongoDB\Database::class, $connection->getMongoDB()); $this->assertInstanceOf(Database::class, $connection->getMongoDB());
$this->assertInstanceOf(Client::class, $connection->getMongoClient());
}
$connection = DB::connection('mongodb'); public function testDsnDb()
$this->assertInstanceOf(\MongoDB\Client::class, $connection->getMongoClient()); {
$connection = DB::connection('dsn_mongodb_db');
$this->assertInstanceOf(Database::class, $connection->getMongoDB());
$this->assertInstanceOf(Client::class, $connection->getMongoClient());
} }
public function testCollection() public function testCollection()
{ {
$collection = DB::connection('mongodb')->getCollection('unittest'); $collection = DB::connection('mongodb')->getCollection('unittest');
$this->assertInstanceOf(Jenssegers\Mongodb\Collection::class, $collection); $this->assertInstanceOf(Collection::class, $collection);
$collection = DB::connection('mongodb')->collection('unittests'); $collection = DB::connection('mongodb')->collection('unittests');
$this->assertInstanceOf(Jenssegers\Mongodb\Query\Builder::class, $collection); $this->assertInstanceOf(Builder::class, $collection);
$collection = DB::connection('mongodb')->table('unittests'); $collection = DB::connection('mongodb')->table('unittests');
$this->assertInstanceOf(Jenssegers\Mongodb\Query\Builder::class, $collection); $this->assertInstanceOf(Builder::class, $collection);
} }
// public function testDynamic()
// {
// $dbs = DB::connection('mongodb')->listCollections();
// $this->assertIsArray($dbs);
// }
// public function testMultipleConnections()
// {
// global $app;
// # Add fake host
// $db = $app['config']['database.connections']['mongodb'];
// $db['host'] = array($db['host'], '1.2.3.4');
// $connection = new Connection($db);
// $mongoclient = $connection->getMongoClient();
// $hosts = $mongoclient->getHosts();
// $this->assertCount(1, $hosts);
// }
public function testQueryLog() public function testQueryLog()
{ {
DB::enableQueryLog(); DB::enableQueryLog();
...@@ -90,7 +80,7 @@ class ConnectionTest extends TestCase ...@@ -90,7 +80,7 @@ class ConnectionTest extends TestCase
public function testSchemaBuilder() public function testSchemaBuilder()
{ {
$schema = DB::connection('mongodb')->getSchemaBuilder(); $schema = DB::connection('mongodb')->getSchemaBuilder();
$this->assertInstanceOf(\Jenssegers\Mongodb\Schema\Builder::class, $schema); $this->assertInstanceOf(SchemaBuilder::class, $schema);
} }
public function testDriverName() public function testDriverName()
......
...@@ -42,7 +42,7 @@ class EmbeddedRelationsTest extends TestCase ...@@ -42,7 +42,7 @@ class EmbeddedRelationsTest extends TestCase
$address->unsetEventDispatcher(); $address->unsetEventDispatcher();
$this->assertNotNull($user->addresses); $this->assertNotNull($user->addresses);
$this->assertInstanceOf(\Illuminate\Database\Eloquent\Collection::class, $user->addresses); $this->assertInstanceOf(Collection::class, $user->addresses);
$this->assertEquals(['London'], $user->addresses->pluck('city')->all()); $this->assertEquals(['London'], $user->addresses->pluck('city')->all());
$this->assertInstanceOf(DateTime::class, $address->created_at); $this->assertInstanceOf(DateTime::class, $address->created_at);
$this->assertInstanceOf(DateTime::class, $address->updated_at); $this->assertInstanceOf(DateTime::class, $address->updated_at);
...@@ -103,29 +103,6 @@ class EmbeddedRelationsTest extends TestCase ...@@ -103,29 +103,6 @@ class EmbeddedRelationsTest extends TestCase
$this->assertEquals(['London', 'Manhattan', 'Bruxelles'], $freshUser->addresses->pluck('city')->all()); $this->assertEquals(['London', 'Manhattan', 'Bruxelles'], $freshUser->addresses->pluck('city')->all());
} }
// public function testEmbedsManySaveModel()
// {
// $user = User::create(['name' => 'John Doe']);
// $address = new Address(['city' => 'London']);
// $address->setEventDispatcher($events = Mockery::mock(\Illuminate\Events\Dispatcher::class));
// $events->shouldReceive('until')->once()->with('eloquent.saving: ' . get_class($address), $address)->andReturn(true);
// $events->shouldReceive('until')->once()->with('eloquent.creating: ' . get_class($address), $address)->andReturn(true);
// $events->shouldReceive('dispatch')->once()->with('eloquent.created: ' . get_class($address), $address);
// $events->shouldReceive('dispatch')->once()->with('eloquent.saved: ' . get_class($address), $address);
// $address->save();
// $address->setEventDispatcher($events = Mockery::mock(\Illuminate\Events\Dispatcher::class));
// $events->shouldReceive('until')->once()->with('eloquent.saving: ' . get_class($address), $address)->andReturn(true);
// $events->shouldReceive('until')->once()->with('eloquent.updating: ' . get_class($address), $address)->andReturn(true);
// $events->shouldReceive('dispatch')->once()->with('eloquent.updated: ' . get_class($address), $address);
// $events->shouldReceive('dispatch')->once()->with('eloquent.saved: ' . get_class($address), $address);
// $address->city = 'Paris';
// $address->save();
// }
public function testEmbedsToArray() public function testEmbedsToArray()
{ {
$user = User::create(['name' => 'John Doe']); $user = User::create(['name' => 'John Doe']);
...@@ -637,6 +614,36 @@ class EmbeddedRelationsTest extends TestCase ...@@ -637,6 +614,36 @@ class EmbeddedRelationsTest extends TestCase
$this->assertNull($user->father); $this->assertNull($user->father);
} }
public function testEmbedsOneRefresh()
{
$user = User::create(['name' => 'John Doe']);
$father = new User(['name' => 'Mark Doe']);
$user->father()->associate($father);
$user->save();
$user->refresh();
$this->assertNotNull($user->father);
$this->assertEquals('Mark Doe', $user->father->name);
}
public function testEmbedsOneEmptyRefresh()
{
$user = User::create(['name' => 'John Doe']);
$father = new User(['name' => 'Mark Doe']);
$user->father()->associate($father);
$user->save();
$user->father()->dissociate();
$user->save();
$user->refresh();
$this->assertNull($user->father);
}
public function testEmbedsManyToArray() public function testEmbedsManyToArray()
{ {
/** @var User $user */ /** @var User $user */
...@@ -650,6 +657,22 @@ class EmbeddedRelationsTest extends TestCase ...@@ -650,6 +657,22 @@ class EmbeddedRelationsTest extends TestCase
$this->assertIsArray($array['addresses']); $this->assertIsArray($array['addresses']);
} }
public function testEmbedsManyRefresh()
{
/** @var User $user */
$user = User::create(['name' => 'John Doe']);
$user->addresses()->save(new Address(['city' => 'New York']));
$user->addresses()->save(new Address(['city' => 'Paris']));
$user->addresses()->save(new Address(['city' => 'Brussels']));
$user->refresh();
$array = $user->toArray();
$this->assertArrayHasKey('addresses', $array);
$this->assertIsArray($array['addresses']);
}
public function testEmbeddedSave() public function testEmbeddedSave()
{ {
/** @var User $user */ /** @var User $user */
......
...@@ -2,8 +2,10 @@ ...@@ -2,8 +2,10 @@
declare(strict_types=1); declare(strict_types=1);
use Carbon\Carbon; use Carbon\Carbon;
use Illuminate\Database\Eloquent\Collection; use Illuminate\Database\Eloquent\Collection as EloquentCollection;
use Illuminate\Database\Eloquent\ModelNotFoundException; use Illuminate\Database\Eloquent\ModelNotFoundException;
use Jenssegers\Mongodb\Collection;
use Jenssegers\Mongodb\Connection;
use Jenssegers\Mongodb\Eloquent\Model; use Jenssegers\Mongodb\Eloquent\Model;
use MongoDB\BSON\ObjectID; use MongoDB\BSON\ObjectID;
use MongoDB\BSON\UTCDateTime; use MongoDB\BSON\UTCDateTime;
...@@ -22,7 +24,7 @@ class ModelTest extends TestCase ...@@ -22,7 +24,7 @@ class ModelTest extends TestCase
{ {
$user = new User; $user = new User;
$this->assertInstanceOf(Model::class, $user); $this->assertInstanceOf(Model::class, $user);
$this->assertInstanceOf(\Jenssegers\Mongodb\Connection::class, $user->getConnection()); $this->assertInstanceOf(Connection::class, $user->getConnection());
$this->assertFalse($user->exists); $this->assertFalse($user->exists);
$this->assertEquals('users', $user->getTable()); $this->assertEquals('users', $user->getTable());
$this->assertEquals('_id', $user->getKeyName()); $this->assertEquals('_id', $user->getKeyName());
...@@ -196,7 +198,7 @@ class ModelTest extends TestCase ...@@ -196,7 +198,7 @@ class ModelTest extends TestCase
$users = User::get(); $users = User::get();
$this->assertCount(2, $users); $this->assertCount(2, $users);
$this->assertInstanceOf(Collection::class, $users); $this->assertInstanceOf(EloquentCollection::class, $users);
$this->assertInstanceOf(Model::class, $users[0]); $this->assertInstanceOf(Model::class, $users[0]);
} }
...@@ -216,7 +218,7 @@ class ModelTest extends TestCase ...@@ -216,7 +218,7 @@ class ModelTest extends TestCase
public function testNoDocument(): void public function testNoDocument(): void
{ {
$items = Item::where('name', 'nothing')->get(); $items = Item::where('name', 'nothing')->get();
$this->assertInstanceOf(Collection::class, $items); $this->assertInstanceOf(EloquentCollection::class, $items);
$this->assertEquals(0, $items->count()); $this->assertEquals(0, $items->count());
$item = Item::where('name', 'nothing')->first(); $item = Item::where('name', 'nothing')->first();
...@@ -440,11 +442,11 @@ class ModelTest extends TestCase ...@@ -440,11 +442,11 @@ class ModelTest extends TestCase
public function testCarbonDateMockingWorks() public function testCarbonDateMockingWorks()
{ {
$fakeDate = \Carbon\Carbon::createFromDate(2000, 01, 01); $fakeDate = Carbon::createFromDate(2000, 01, 01);
Carbon::setTestNow($fakeDate); Carbon::setTestNow($fakeDate);
$item = Item::create(['name' => 'sword']); $item = Item::create(['name' => 'sword']);
$this->assertLessThan(1, $fakeDate->diffInSeconds($item->created_at)); $this->assertLessThan(1, $fakeDate->diffInSeconds($item->created_at));
} }
...@@ -491,24 +493,24 @@ class ModelTest extends TestCase ...@@ -491,24 +493,24 @@ class ModelTest extends TestCase
User::create(['name' => 'Jane Doe', 'age' => 35]); User::create(['name' => 'Jane Doe', 'age' => 35]);
User::create(['name' => 'Harry Hoe', 'age' => 15]); User::create(['name' => 'Harry Hoe', 'age' => 15]);
$users = User::raw(function (\Jenssegers\Mongodb\Collection $collection) { $users = User::raw(function (Collection $collection) {
return $collection->find(['age' => 35]); return $collection->find(['age' => 35]);
}); });
$this->assertInstanceOf(Collection::class, $users); $this->assertInstanceOf(EloquentCollection::class, $users);
$this->assertInstanceOf(Model::class, $users[0]); $this->assertInstanceOf(Model::class, $users[0]);
$user = User::raw(function (\Jenssegers\Mongodb\Collection $collection) { $user = User::raw(function (Collection $collection) {
return $collection->findOne(['age' => 35]); return $collection->findOne(['age' => 35]);
}); });
$this->assertInstanceOf(Model::class, $user); $this->assertInstanceOf(Model::class, $user);
$count = User::raw(function (\Jenssegers\Mongodb\Collection $collection) { $count = User::raw(function (Collection $collection) {
return $collection->count(); return $collection->count();
}); });
$this->assertEquals(3, $count); $this->assertEquals(3, $count);
$result = User::raw(function (\Jenssegers\Mongodb\Collection $collection) { $result = User::raw(function (Collection $collection) {
return $collection->insertOne(['name' => 'Yvonne Yoe', 'age' => 35]); return $collection->insertOne(['name' => 'Yvonne Yoe', 'age' => 35]);
}); });
$this->assertNotNull($result); $this->assertNotNull($result);
...@@ -570,7 +572,7 @@ class ModelTest extends TestCase ...@@ -570,7 +572,7 @@ class ModelTest extends TestCase
User::create(['name' => 'spoon', 'tags' => ['round', 'bowl']]); User::create(['name' => 'spoon', 'tags' => ['round', 'bowl']]);
$count = 0; $count = 0;
User::chunkById(2, function (\Illuminate\Database\Eloquent\Collection $items) use (&$count) { User::chunkById(2, function (EloquentCollection $items) use (&$count) {
$count += count($items); $count += count($items);
}); });
......
<?php <?php
declare(strict_types=1); declare(strict_types=1);
use Illuminate\Support\Facades\Date;
use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\DB;
use Illuminate\Support\LazyCollection;
use Jenssegers\Mongodb\Collection; use Jenssegers\Mongodb\Collection;
use Jenssegers\Mongodb\Query\Builder; use Jenssegers\Mongodb\Query\Builder;
use MongoDB\BSON\ObjectId; use MongoDB\BSON\ObjectId;
...@@ -150,7 +152,6 @@ class QueryBuilderTest extends TestCase ...@@ -150,7 +152,6 @@ class QueryBuilderTest extends TestCase
]); ]);
DB::collection('users')->where('name', 'John Doe')->update(['age' => 100]); DB::collection('users')->where('name', 'John Doe')->update(['age' => 100]);
$users = DB::collection('users')->get();
$john = DB::collection('users')->where('name', 'John Doe')->first(); $john = DB::collection('users')->where('name', 'John Doe')->first();
$jane = DB::collection('users')->where('name', 'Jane Doe')->first(); $jane = DB::collection('users')->where('name', 'Jane Doe')->first();
...@@ -545,14 +546,14 @@ class QueryBuilderTest extends TestCase ...@@ -545,14 +546,14 @@ class QueryBuilderTest extends TestCase
public function testDates() public function testDates()
{ {
DB::collection('users')->insert([ DB::collection('users')->insert([
['name' => 'John Doe', 'birthday' => new UTCDateTime(1000 * strtotime("1980-01-01 00:00:00"))], ['name' => 'John Doe', 'birthday' => new UTCDateTime(Date::parse("1980-01-01 00:00:00")->format('Uv'))],
['name' => 'Jane Doe', 'birthday' => new UTCDateTime(1000 * strtotime("1981-01-01 00:00:00"))], ['name' => 'Jane Doe', 'birthday' => new UTCDateTime(Date::parse("1981-01-01 00:00:00")->format('Uv'))],
['name' => 'Robert Roe', 'birthday' => new UTCDateTime(1000 * strtotime("1982-01-01 00:00:00"))], ['name' => 'Robert Roe', 'birthday' => new UTCDateTime(Date::parse("1982-01-01 00:00:00")->format('Uv'))],
['name' => 'Mark Moe', 'birthday' => new UTCDateTime(1000 * strtotime("1983-01-01 00:00:00"))], ['name' => 'Mark Moe', 'birthday' => new UTCDateTime(Date::parse("1983-01-01 00:00:00")->format('Uv'))],
]); ]);
$user = DB::collection('users') $user = DB::collection('users')
->where('birthday', new UTCDateTime(1000 * strtotime("1980-01-01 00:00:00"))) ->where('birthday', new UTCDateTime(Date::parse("1980-01-01 00:00:00")->format('Uv')))
->first(); ->first();
$this->assertEquals('John Doe', $user['name']); $this->assertEquals('John Doe', $user['name']);
...@@ -759,4 +760,21 @@ class QueryBuilderTest extends TestCase ...@@ -759,4 +760,21 @@ class QueryBuilderTest extends TestCase
$this->assertEquals('spork', $results[1]['name']); $this->assertEquals('spork', $results[1]['name']);
$this->assertEquals('fork', $results[0]['name']); $this->assertEquals('fork', $results[0]['name']);
} }
public function testCursor()
{
$data = [
['name' => 'fork', 'tags' => ['sharp', 'pointy']],
['name' => 'spork', 'tags' => ['sharp', 'pointy', 'round', 'bowl']],
['name' => 'spoon', 'tags' => ['round', 'bowl']],
];
DB::collection('items')->insert($data);
$results = DB::collection('items')->orderBy('_id', 'asc')->cursor();
$this->assertInstanceOf(LazyCollection::class, $results);
foreach ($results as $i => $result) {
$this->assertEquals($data[$i]['name'], $result['name']);
}
}
} }
...@@ -69,6 +69,15 @@ class QueryTest extends TestCase ...@@ -69,6 +69,15 @@ class QueryTest extends TestCase
$users = User::where('name', 'like', 't%')->get(); $users = User::where('name', 'like', 't%')->get();
$this->assertCount(1, $users); $this->assertCount(1, $users);
$users = User::where('age', 'like', '%35%')->get();
$this->assertCount(3, $users);
$users = User::where('age', 'like', '3%')->get();
$this->assertCount(6, $users);
$users = User::where('age', 'like', '%3')->get();
$this->assertCount(4, $users);
} }
public function testNotLike(): void public function testNotLike(): void
......
<?php <?php
declare(strict_types=1); declare(strict_types=1);
use Carbon\Carbon;
use Jenssegers\Mongodb\Queue\Failed\MongoFailedJobProvider; use Jenssegers\Mongodb\Queue\Failed\MongoFailedJobProvider;
class QueueTest extends TestCase class QueueTest extends TestCase
...@@ -43,7 +44,7 @@ class QueueTest extends TestCase ...@@ -43,7 +44,7 @@ class QueueTest extends TestCase
$this->assertNotNull($id); $this->assertNotNull($id);
// Expire the test job // Expire the test job
$expiry = \Carbon\Carbon::now()->subSeconds(Config::get('queue.connections.database.expire'))->getTimestamp(); $expiry = Carbon::now()->subSeconds(Config::get('queue.connections.database.expire'))->getTimestamp();
Queue::getDatabase() Queue::getDatabase()
->table(Config::get('queue.connections.database.table')) ->table(Config::get('queue.connections.database.table'))
->where('_id', $id) ->where('_id', $id)
......
...@@ -296,10 +296,10 @@ class RelationsTest extends TestCase ...@@ -296,10 +296,10 @@ class RelationsTest extends TestCase
public function testBelongsToManyAttachEloquentCollection(): void public function testBelongsToManyAttachEloquentCollection(): void
{ {
$user = User::create(['name' => 'John Doe']); User::create(['name' => 'John Doe']);
$client1 = Client::create(['name' => 'Test 1']); $client1 = Client::create(['name' => 'Test 1']);
$client2 = Client::create(['name' => 'Test 2']); $client2 = Client::create(['name' => 'Test 2']);
$collection = new \Illuminate\Database\Eloquent\Collection([$client1, $client2]); $collection = new Collection([$client1, $client2]);
$user = User::where('name', '=', 'John Doe')->first(); $user = User::where('name', '=', 'John Doe')->first();
$user->clients()->attach($collection); $user->clients()->attach($collection);
...@@ -467,7 +467,7 @@ class RelationsTest extends TestCase ...@@ -467,7 +467,7 @@ class RelationsTest extends TestCase
], ],
]); ]);
$address = $client->addresses()->create([ $client->addresses()->create([
'data' => [ 'data' => [
'address_id' => 1432, 'address_id' => 1432,
'city' => 'Paris', 'city' => 'Paris',
......
...@@ -53,6 +53,7 @@ class TestCase extends Orchestra\Testbench\TestCase ...@@ -53,6 +53,7 @@ class TestCase extends Orchestra\Testbench\TestCase
$app['config']->set('database.connections.mongodb', $config['connections']['mongodb']); $app['config']->set('database.connections.mongodb', $config['connections']['mongodb']);
$app['config']->set('database.connections.mongodb2', $config['connections']['mongodb']); $app['config']->set('database.connections.mongodb2', $config['connections']['mongodb']);
$app['config']->set('database.connections.dsn_mongodb', $config['connections']['dsn_mongodb']); $app['config']->set('database.connections.dsn_mongodb', $config['connections']['dsn_mongodb']);
$app['config']->set('database.connections.dsn_mongodb_db', $config['connections']['dsn_mongodb_db']);
$app['config']->set('auth.model', 'User'); $app['config']->set('auth.model', 'User');
$app['config']->set('auth.providers.users.model', 'User'); $app['config']->set('auth.providers.users.model', 'User');
......
...@@ -21,6 +21,11 @@ return [ ...@@ -21,6 +21,11 @@ return [
'database' => env('MONGO_DATABASE', 'unittest'), 'database' => env('MONGO_DATABASE', 'unittest'),
], ],
'dsn_mongodb_db' => [
'driver' => 'mongodb',
'dsn' => "mongodb://$mongoHost:$mongoPort/" . env('MONGO_DATABASE', 'unittest'),
],
'mysql' => [ 'mysql' => [
'driver' => 'mysql', 'driver' => 'mysql',
'host' => env('MYSQL_HOST', 'mysql'), 'host' => env('MYSQL_HOST', 'mysql'),
......
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