Commit 13859bb5 authored by Jens Segers's avatar Jens Segers

Add styleci

parent 52145b0c
preset: psr2
enabled:
- duplicate_semicolon
- empty_return
- extra_empty_lines
- operators_spaces
- phpdoc_indent
- remove_leading_slash_use
- spaces_cast
- ternary_spaces
- unused_use
disabled:
- braces
- parenthesis
...@@ -13,13 +13,13 @@ use Jenssegers\Mongodb\Query\Builder as QueryBuilder; ...@@ -13,13 +13,13 @@ use Jenssegers\Mongodb\Query\Builder as QueryBuilder;
abstract class Model extends \Illuminate\Database\Eloquent\Model { abstract class Model extends \Illuminate\Database\Eloquent\Model {
/** /**
* Define a one-to-one relationship. * Define a one-to-one relationship.
* *
* @param string $related * @param string $related
* @param string $foreignKey * @param string $foreignKey
* @param string $localKey * @param string $localKey
* @return \Illuminate\Database\Eloquent\Relations\HasOne * @return \Illuminate\Database\Eloquent\Relations\HasOne
*/ */
public function hasOne($related, $foreignKey = null, $localKey = null) public function hasOne($related, $foreignKey = null, $localKey = null)
{ {
// Check if it is a relation with an original model. // Check if it is a relation with an original model.
...@@ -67,13 +67,13 @@ abstract class Model extends \Illuminate\Database\Eloquent\Model { ...@@ -67,13 +67,13 @@ abstract class Model extends \Illuminate\Database\Eloquent\Model {
} }
/** /**
* Define a one-to-many relationship. * Define a one-to-many relationship.
* *
* @param string $related * @param string $related
* @param string $foreignKey * @param string $foreignKey
* @param string $localKey * @param string $localKey
* @return \Illuminate\Database\Eloquent\Relations\HasMany * @return \Illuminate\Database\Eloquent\Relations\HasMany
*/ */
public function hasMany($related, $foreignKey = null, $localKey = null) public function hasMany($related, $foreignKey = null, $localKey = null)
{ {
// Check if it is a relation with an original model. // Check if it is a relation with an original model.
...@@ -124,14 +124,14 @@ abstract class Model extends \Illuminate\Database\Eloquent\Model { ...@@ -124,14 +124,14 @@ abstract class Model extends \Illuminate\Database\Eloquent\Model {
} }
/** /**
* Define an inverse one-to-one or many relationship. * Define an inverse one-to-one or many relationship.
* *
* @param string $related * @param string $related
* @param string $foreignKey * @param string $foreignKey
* @param string $otherKey * @param string $otherKey
* @param string $relation * @param string $relation
* @return \Illuminate\Database\Eloquent\Relations\BelongsTo * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
*/ */
public function belongsTo($related, $foreignKey = null, $otherKey = null, $relation = null) public function belongsTo($related, $foreignKey = null, $otherKey = null, $relation = null)
{ {
// If no relation name was given, we will use this debug backtrace to extract // If no relation name was given, we will use this debug backtrace to extract
......
...@@ -5,37 +5,37 @@ use MongoDate; ...@@ -5,37 +5,37 @@ use MongoDate;
class DatabaseTokenRepository extends \Illuminate\Auth\Passwords\DatabaseTokenRepository { class DatabaseTokenRepository extends \Illuminate\Auth\Passwords\DatabaseTokenRepository {
/** /**
* Build the record payload for the table. * Build the record payload for the table.
* *
* @param string $email * @param string $email
* @param string $token * @param string $token
* @return array * @return array
*/ */
protected function getPayload($email, $token) protected function getPayload($email, $token)
{ {
return ['email' => $email, 'token' => $token, 'created_at' => new MongoDate]; return ['email' => $email, 'token' => $token, 'created_at' => new MongoDate];
} }
/** /**
* Determine if the token has expired. * Determine if the token has expired.
* *
* @param array $token * @param array $token
* @return bool * @return bool
*/ */
protected function tokenExpired($token) protected function tokenExpired($token)
{ {
// Convert MongoDate to a date string. // Convert MongoDate to a date string.
if ($token['created_at'] instanceof MongoDate) if ($token['created_at'] instanceof MongoDate)
{ {
$date = new DateTime; $date = new DateTime;
$date->setTimestamp($token['created_at']->sec); $date->setTimestamp($token['created_at']->sec);
$token['created_at'] = $date->format('Y-m-d H:i:s'); $token['created_at'] = $date->format('Y-m-d H:i:s');
} }
return parent::tokenExpired($token); return parent::tokenExpired($token);
} }
} }
...@@ -4,26 +4,26 @@ use Jenssegers\Mongodb\Auth\DatabaseTokenRepository as DbRepository; ...@@ -4,26 +4,26 @@ use Jenssegers\Mongodb\Auth\DatabaseTokenRepository as DbRepository;
class PasswordResetServiceProvider extends \Illuminate\Auth\Passwords\PasswordResetServiceProvider { class PasswordResetServiceProvider extends \Illuminate\Auth\Passwords\PasswordResetServiceProvider {
/** /**
* Register the token repository implementation. * Register the token repository implementation.
* *
* @return void * @return void
*/ */
protected function registerTokenRepository() protected function registerTokenRepository()
{ {
$this->app->singleton('auth.password.tokens', function($app) $this->app->singleton('auth.password.tokens', function ($app)
{ {
$connection = $app['db']->connection(); $connection = $app['db']->connection();
// The database token repository is an implementation of the token repository // The database token repository is an implementation of the token repository
// interface, and is responsible for the actual storing of auth tokens and // interface, and is responsible for the actual storing of auth tokens and
// their e-mail addresses. We will inject this table and hash key to it. // their e-mail addresses. We will inject this table and hash key to it.
$table = $app['config']['auth.password.table']; $table = $app['config']['auth.password.table'];
$key = $app['config']['app.key']; $key = $app['config']['app.key'];
$expire = $app['config']->get('auth.password.expire', 60); $expire = $app['config']->get('auth.password.expire', 60);
return new DbRepository($connection, $table, $key, $expire); return new DbRepository($connection, $table, $key, $expire);
}); });
} }
} }
<?php namespace Jenssegers\Mongodb; <?php namespace Jenssegers\Mongodb;
use Exception, MongoCollection; use Exception;
use Jenssegers\Mongodb\Connection; use MongoCollection;
class Collection { class Collection {
...@@ -63,7 +63,7 @@ class Collection { ...@@ -63,7 +63,7 @@ class Collection {
} }
} }
$queryString = $this->collection->getName() . '.' . $method . '(' . join(',', $query) . ')'; $queryString = $this->collection->getName() . '.' . $method . '(' . implode(',', $query) . ')';
$this->connection->logQuery($queryString, [], $time); $this->connection->logQuery($queryString, [], $time);
} }
......
...@@ -111,7 +111,7 @@ class Connection extends \Illuminate\Database\Connection { ...@@ -111,7 +111,7 @@ class Connection extends \Illuminate\Database\Connection {
} }
/** /**
* return MongoClient object * return MongoClient object.
* *
* @return MongoClient * @return MongoClient
*/ */
...@@ -211,10 +211,10 @@ class Connection extends \Illuminate\Database\Connection { ...@@ -211,10 +211,10 @@ class Connection extends \Illuminate\Database\Connection {
} }
/** /**
* Get the PDO driver name. * Get the PDO driver name.
* *
* @return string * @return string
*/ */
public function getDriverName() public function getDriverName()
{ {
return 'mongodb'; return 'mongodb';
......
...@@ -13,7 +13,7 @@ class Builder extends EloquentBuilder { ...@@ -13,7 +13,7 @@ class Builder extends EloquentBuilder {
*/ */
protected $passthru = array( protected $passthru = array(
'toSql', 'lists', 'insert', 'insertGetId', 'pluck', 'toSql', 'lists', 'insert', 'insertGetId', 'pluck',
'count', 'min', 'max', 'avg', 'sum', 'exists', 'push', 'pull' 'count', 'min', 'max', 'avg', 'sum', 'exists', 'push', 'pull',
); );
/** /**
...@@ -174,7 +174,7 @@ class Builder extends EloquentBuilder { ...@@ -174,7 +174,7 @@ class Builder extends EloquentBuilder {
$relationCount = array_count_values($query->lists($relation->getHasCompareKey())); $relationCount = array_count_values($query->lists($relation->getHasCompareKey()));
// Remove unwanted related objects based on the operator and count. // Remove unwanted related objects based on the operator and count.
$relationCount = array_filter($relationCount, function($counted) use ($count, $operator) $relationCount = array_filter($relationCount, function ($counted) use ($count, $operator)
{ {
// If we are comparing to 0, we always need all results. // If we are comparing to 0, we always need all results.
if ($count == 0) return true; if ($count == 0) return true;
...@@ -213,29 +213,29 @@ class Builder extends EloquentBuilder { ...@@ -213,29 +213,29 @@ class Builder extends EloquentBuilder {
* @return mixed * @return mixed
*/ */
public function raw($expression = null) public function raw($expression = null)
{ {
// Get raw results from the query builder. // Get raw results from the query builder.
$results = $this->query->raw($expression); $results = $this->query->raw($expression);
// Convert MongoCursor results to a collection of models. // Convert MongoCursor results to a collection of models.
if ($results instanceof MongoCursor) if ($results instanceof MongoCursor)
{ {
$results = iterator_to_array($results, false); $results = iterator_to_array($results, false);
return $this->model->hydrate($results); return $this->model->hydrate($results);
} }
// The result is a single object. // The result is a single object.
else if (is_array($results) and array_key_exists('_id', $results)) elseif (is_array($results) and array_key_exists('_id', $results))
{ {
$model = $this->model->newFromBuilder($results); $model = $this->model->newFromBuilder($results);
$model->setConnection($this->model->getConnection()); $model->setConnection($this->model->getConnection());
return $model; return $model;
} }
return $results; return $results;
} }
} }
...@@ -40,7 +40,7 @@ class Collection extends EloquentCollection { ...@@ -40,7 +40,7 @@ class Collection extends EloquentCollection {
list($value, $operator) = array($operator, '='); list($value, $operator) = array($operator, '=');
} }
return $this->filter(function($item) use ($key, $operator, $value) return $this->filter(function ($item) use ($key, $operator, $value)
{ {
$actual = $item->{$key}; $actual = $item->{$key};
......
...@@ -2,16 +2,16 @@ ...@@ -2,16 +2,16 @@
trait SoftDeletes { trait SoftDeletes {
use \Illuminate\Database\Eloquent\SoftDeletes; use \Illuminate\Database\Eloquent\SoftDeletes;
/** /**
* Get the fully qualified "deleted at" column. * Get the fully qualified "deleted at" column.
* *
* @return string * @return string
*/ */
public function getQualifiedDeletedAtColumn() public function getQualifiedDeletedAtColumn()
{ {
return $this->getDeletedAtColumn(); return $this->getDeletedAtColumn();
} }
} }
<?php namespace Jenssegers\Mongodb; <?php namespace Jenssegers\Mongodb;
use DateTime, MongoId, MongoDate, Carbon\Carbon; use DateTime;
use MongoId;
use MongoDate;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Relations\Relation; use Illuminate\Database\Eloquent\Relations\Relation;
use Jenssegers\Mongodb\DatabaseManager as Resolver;
use Jenssegers\Mongodb\Eloquent\Builder; use Jenssegers\Mongodb\Eloquent\Builder;
use Jenssegers\Mongodb\Relations\EmbedsOneOrMany; use Jenssegers\Mongodb\Relations\EmbedsOneOrMany;
use Jenssegers\Mongodb\Relations\EmbedsMany; use Jenssegers\Mongodb\Relations\EmbedsMany;
...@@ -63,10 +65,9 @@ abstract class Model extends \Jenssegers\Eloquent\Model { ...@@ -63,10 +65,9 @@ abstract class Model extends \Jenssegers\Eloquent\Model {
*/ */
public function getQualifiedKeyName() public function getQualifiedKeyName()
{ {
return $this->getKeyName(); return $this->getKeyName();
} }
/** /**
* Define an embedded one-to-many relationship. * Define an embedded one-to-many relationship.
* *
...@@ -306,7 +307,9 @@ abstract class Model extends \Jenssegers\Eloquent\Model { ...@@ -306,7 +307,9 @@ abstract class Model extends \Jenssegers\Eloquent\Model {
$value = $this->fromDateTime($value); $value = $this->fromDateTime($value);
} }
array_set($this->attributes, $key, $value); return; array_set($this->attributes, $key, $value);
return;
} }
parent::setAttribute($key, $value); parent::setAttribute($key, $value);
......
<?php namespace Jenssegers\Mongodb; <?php namespace Jenssegers\Mongodb;
use Jenssegers\Mongodb\Model; use Illuminate\Support\ServiceProvider;
use Jenssegers\Mongodb\DatabaseManager;
use Illuminate\Support\ServiceProvider; class MongodbServiceProvider extends ServiceProvider {
class MongodbServiceProvider extends ServiceProvider { /**
* Bootstrap the application events.
/** *
* Bootstrap the application events. * @return void
* */
* @return void public function boot()
*/ {
public function boot() Model::setConnectionResolver($this->app['db']);
{
Model::setConnectionResolver($this->app['db']); Model::setEventDispatcher($this->app['events']);
}
Model::setEventDispatcher($this->app['events']);
} /**
* Register the service provider.
/** *
* Register the service provider. * @return void
* */
* @return void public function register()
*/ {
public function register() $this->app->resolving('db', function ($db)
{ {
$this->app->resolving('db', function($db) $db->extend('mongodb', function ($config)
{ {
$db->extend('mongodb', function($config) return new Connection($config);
{ });
return new Connection($config); });
}); }
});
} }
}
<?php namespace Jenssegers\Mongodb\Query; <?php namespace Jenssegers\Mongodb\Query;
use MongoId, MongoRegex, MongoDate, DateTime, Closure; use MongoId;
use MongoRegex;
use MongoDate;
use DateTime;
use Closure;
use Illuminate\Database\Query\Builder as BaseBuilder; use Illuminate\Database\Query\Builder as BaseBuilder;
use Illuminate\Database\Query\Expression; use Illuminate\Database\Query\Expression;
use Illuminate\Support\Collection; use Illuminate\Support\Collection;
...@@ -9,7 +13,7 @@ use Jenssegers\Mongodb\Connection; ...@@ -9,7 +13,7 @@ use Jenssegers\Mongodb\Connection;
class Builder extends BaseBuilder { class Builder extends BaseBuilder {
/** /**
* The database collection * The database collection.
* *
* @var MongoCollection * @var MongoCollection
*/ */
...@@ -28,7 +32,7 @@ class Builder extends BaseBuilder { ...@@ -28,7 +32,7 @@ class Builder extends BaseBuilder {
* @var int * @var int
*/ */
public $timeout; public $timeout;
/** /**
* The cursor hint value. * The cursor hint value.
* *
...@@ -110,7 +114,7 @@ class Builder extends BaseBuilder { ...@@ -110,7 +114,7 @@ class Builder extends BaseBuilder {
return $this; return $this;
} }
/** /**
* Set the cursor hint. * Set the cursor hint.
* *
...@@ -248,7 +252,7 @@ class Builder extends BaseBuilder { ...@@ -248,7 +252,7 @@ class Builder extends BaseBuilder {
} }
// Distinct query // Distinct query
else if ($this->distinct) elseif ($this->distinct)
{ {
// Return distinct results directly // Return distinct results directly
$column = isset($this->columns[0]) ? $this->columns[0] : '_id'; $column = isset($this->columns[0]) ? $this->columns[0] : '_id';
...@@ -507,7 +511,7 @@ class Builder extends BaseBuilder { ...@@ -507,7 +511,7 @@ class Builder extends BaseBuilder {
} }
// Protect // Protect
$this->where(function($query) use ($column) $this->where(function ($query) use ($column)
{ {
$query->where($column, 'exists', false); $query->where($column, 'exists', false);
...@@ -612,7 +616,7 @@ class Builder extends BaseBuilder { ...@@ -612,7 +616,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 MongoId'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'];
...@@ -640,7 +644,7 @@ class Builder extends BaseBuilder { ...@@ -640,7 +644,7 @@ class Builder extends BaseBuilder {
} }
// Create an expression for the given value // Create an expression for the given value
else if ( ! is_null($expression)) elseif ( ! is_null($expression))
{ {
return new Expression($expression); return new Expression($expression);
} }
...@@ -668,7 +672,7 @@ class Builder extends BaseBuilder { ...@@ -668,7 +672,7 @@ class Builder extends BaseBuilder {
{ {
$query = array($operator => $column); $query = array($operator => $column);
} }
else if ($batch) elseif ($batch)
{ {
$query = array($operator => array($column => array('$each' => $value))); $query = array($operator => array($column => array('$each' => $value)));
} }
...@@ -833,14 +837,14 @@ class Builder extends BaseBuilder { ...@@ -833,14 +837,14 @@ class Builder extends BaseBuilder {
// Operator conversions // Operator conversions
$convert = array( $convert = array(
'regexp' => 'regex', 'regexp' => 'regex',
'elemmatch' => 'elemMatch', 'elemmatch' => 'elemMatch',
'geointersects' => 'geoIntersects', 'geointersects' => 'geoIntersects',
'geowithin' => 'geoWithin', 'geowithin' => 'geoWithin',
'nearsphere' => 'nearSphere', 'nearsphere' => 'nearSphere',
'maxdistance' => 'maxDistance', 'maxdistance' => 'maxDistance',
'centersphere' => 'centerSphere', 'centersphere' => 'centerSphere',
'uniquedocs' => 'uniqueDocs', 'uniquedocs' => 'uniqueDocs',
); );
if (array_key_exists($where['operator'], $convert)) if (array_key_exists($where['operator'], $convert))
...@@ -862,7 +866,7 @@ class Builder extends BaseBuilder { ...@@ -862,7 +866,7 @@ class Builder extends BaseBuilder {
} }
// Single value. // Single value.
else if (isset($where['value'])) elseif (isset($where['value']))
{ {
$where['value'] = $this->convertKey($where['value']); $where['value'] = $this->convertKey($where['value']);
} }
...@@ -879,7 +883,7 @@ class Builder extends BaseBuilder { ...@@ -879,7 +883,7 @@ class Builder extends BaseBuilder {
// use the operator of the next where. // use the operator of the next where.
if ($i == 0 and count($wheres) > 1 and $where['boolean'] == 'and') if ($i == 0 and count($wheres) > 1 and $where['boolean'] == 'and')
{ {
$where['boolean'] = $wheres[$i+1]['boolean']; $where['boolean'] = $wheres[$i + 1]['boolean'];
} }
// We use different methods to compile different wheres. // We use different methods to compile different wheres.
...@@ -894,7 +898,7 @@ class Builder extends BaseBuilder { ...@@ -894,7 +898,7 @@ class Builder extends BaseBuilder {
// If there are multiple wheres, we will wrap it with $and. This is needed // If there are multiple wheres, we will wrap it with $and. This is needed
// to make nested wheres work. // to make nested wheres work.
else if (count($wheres) > 1) elseif (count($wheres) > 1)
{ {
$result = array('$and' => array($result)); $result = array('$and' => array($result));
} }
...@@ -944,7 +948,7 @@ class Builder extends BaseBuilder { ...@@ -944,7 +948,7 @@ class Builder extends BaseBuilder {
{ {
$query = array($column => $value); $query = array($column => $value);
} }
else if (array_key_exists($operator, $this->conversion)) elseif (array_key_exists($operator, $this->conversion))
{ {
$query = array($column => array($this->conversion[$operator] => $value)); $query = array($column => array($this->conversion[$operator] => $value));
} }
...@@ -1003,15 +1007,15 @@ class Builder extends BaseBuilder { ...@@ -1003,15 +1007,15 @@ class Builder extends BaseBuilder {
'$or' => array( '$or' => array(
array( array(
$column => array( $column => array(
'$lte' => $values[0] '$lte' => $values[0],
) ),
), ),
array( array(
$column => array( $column => array(
'$gte' => $values[1] '$gte' => $values[1],
) ),
) ),
) ),
); );
} }
else else
...@@ -1019,8 +1023,8 @@ class Builder extends BaseBuilder { ...@@ -1019,8 +1023,8 @@ class Builder extends BaseBuilder {
return array( return array(
$column => array( $column => array(
'$gte' => $values[0], '$gte' => $values[0],
'$lte' => $values[1] '$lte' => $values[1],
) ),
); );
} }
} }
......
...@@ -4,5 +4,4 @@ use Illuminate\Database\Query\Processors\Processor as BaseProcessor; ...@@ -4,5 +4,4 @@ use Illuminate\Database\Query\Processors\Processor as BaseProcessor;
class Processor extends BaseProcessor { class Processor extends BaseProcessor {
} }
...@@ -2,36 +2,36 @@ ...@@ -2,36 +2,36 @@
class BelongsTo extends \Illuminate\Database\Eloquent\Relations\BelongsTo { class BelongsTo extends \Illuminate\Database\Eloquent\Relations\BelongsTo {
/** /**
* Set the base constraints on the relation query. * Set the base constraints on the relation query.
* *
* @return void * @return void
*/ */
public function addConstraints() public function addConstraints()
{ {
if (static::$constraints) if (static::$constraints)
{ {
// For belongs to relationships, which are essentially the inverse of has one // For belongs to relationships, which are essentially the inverse of has one
// or has many relationships, we need to actually query on the primary key // or has many relationships, we need to actually query on the primary key
// of the related models matching on the foreign key that's on a parent. // of the related models matching on the foreign key that's on a parent.
$this->query->where($this->otherKey, '=', $this->parent->{$this->foreignKey}); $this->query->where($this->otherKey, '=', $this->parent->{$this->foreignKey});
} }
} }
/** /**
* Set the constraints for an eager load of the relation. * Set the constraints for an eager load of the relation.
* *
* @param array $models * @param array $models
* @return void * @return void
*/ */
public function addEagerConstraints(array $models) public function addEagerConstraints(array $models)
{ {
// We'll grab the primary key name of the related models since it could be set to // We'll grab the primary key name of the related models since it could be set to
// a non-standard name and not "id". We will then construct the constraint for // a non-standard name and not "id". We will then construct the constraint for
// our eagerly loading query so it returns the proper models from execution. // our eagerly loading query so it returns the proper models from execution.
$key = $this->otherKey; $key = $this->otherKey;
$this->query->whereIn($key, $this->getEagerModelKeys($models)); $this->query->whereIn($key, $this->getEagerModelKeys($models));
} }
} }
...@@ -6,283 +6,283 @@ use Illuminate\Database\Eloquent\Relations\BelongsToMany as EloquentBelongsToMan ...@@ -6,283 +6,283 @@ use Illuminate\Database\Eloquent\Relations\BelongsToMany as EloquentBelongsToMan
class BelongsToMany extends EloquentBelongsToMany { class BelongsToMany extends EloquentBelongsToMany {
/** /**
* Hydrate the pivot table relationship on the models. * Hydrate the pivot table relationship on the models.
* *
* @param array $models * @param array $models
* @return void * @return void
*/ */
protected function hydratePivotRelation(array $models) protected function hydratePivotRelation(array $models)
{ {
// Do nothing. // Do nothing.
} }
/** /**
* Set the select clause for the relation query. * Set the select clause for the relation query.
* *
* @param array $columns * @param array $columns
* @return \Illuminate\Database\Eloquent\Relations\BelongsToMany * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
*/ */
protected function getSelectColumns(array $columns = array('*')) protected function getSelectColumns(array $columns = array('*'))
{ {
return $columns; return $columns;
} }
/** /**
* Set the base constraints on the relation query. * Set the base constraints on the relation query.
* *
* @return void * @return void
*/ */
public function addConstraints() public function addConstraints()
{ {
if (static::$constraints) $this->setWhere(); if (static::$constraints) $this->setWhere();
} }
/** /**
* Set the where clause for the relation query. * Set the where clause for the relation query.
* *
* @return $this * @return $this
*/ */
protected function setWhere() protected function setWhere()
{ {
$foreign = $this->getForeignKey(); $foreign = $this->getForeignKey();
$this->query->where($foreign, '=', $this->parent->getKey()); $this->query->where($foreign, '=', $this->parent->getKey());
return $this; return $this;
} }
/** /**
* Save a new model and attach it to the parent model. * Save a new model and attach it to the parent model.
* *
* @param \Illuminate\Database\Eloquent\Model $model * @param \Illuminate\Database\Eloquent\Model $model
* @param array $joining * @param array $joining
* @param bool $touch * @param bool $touch
* @return \Illuminate\Database\Eloquent\Model * @return \Illuminate\Database\Eloquent\Model
*/ */
public function save(Model $model, array $joining = array(), $touch = true) public function save(Model $model, array $joining = array(), $touch = true)
{ {
$model->save(array('touch' => false)); $model->save(array('touch' => false));
$this->attach($model, $joining, $touch); $this->attach($model, $joining, $touch);
return $model; return $model;
} }
/** /**
* Create a new instance of the related model. * Create a new instance of the related model.
* *
* @param array $attributes * @param array $attributes
* @param array $joining * @param array $joining
* @param bool $touch * @param bool $touch
* @return \Illuminate\Database\Eloquent\Model * @return \Illuminate\Database\Eloquent\Model
*/ */
public function create(array $attributes, array $joining = array(), $touch = true) public function create(array $attributes, array $joining = array(), $touch = true)
{ {
$instance = $this->related->newInstance($attributes); $instance = $this->related->newInstance($attributes);
// Once we save the related model, we need to attach it to the base model via // Once we save the related model, we need to attach it to the base model via
// through intermediate table so we'll use the existing "attach" method to // through intermediate table so we'll use the existing "attach" method to
// accomplish this which will insert the record and any more attributes. // accomplish this which will insert the record and any more attributes.
$instance->save(array('touch' => false)); $instance->save(array('touch' => false));
$this->attach($instance, $joining, $touch); $this->attach($instance, $joining, $touch);
return $instance; return $instance;
} }
/** /**
* Sync the intermediate tables with a list of IDs or collection of models. * Sync the intermediate tables with a list of IDs or collection of models.
* *
* @param array $ids * @param array $ids
* @param bool $detaching * @param bool $detaching
* @return array * @return array
*/ */
public function sync($ids, $detaching = true) public function sync($ids, $detaching = true)
{ {
$changes = array( $changes = array(
'attached' => array(), 'detached' => array(), 'updated' => array() 'attached' => array(), 'detached' => array(), 'updated' => array(),
); );
if ($ids instanceof Collection) $ids = $ids->modelKeys(); if ($ids instanceof Collection) $ids = $ids->modelKeys();
// First we need to attach any of the associated models that are not currently // First we need to attach any of the associated models that are not currently
// in this joining table. We'll spin through the given IDs, checking to see // in this joining table. We'll spin through the given IDs, checking to see
// if they exist in the array of current ones, and if not we will insert. // if they exist in the array of current ones, and if not we will insert.
$current = $this->parent->{$this->otherKey} ?: array(); $current = $this->parent->{$this->otherKey} ?: array();
// See issue #256. // See issue #256.
if ($current instanceof Collection) $current = $ids->modelKeys(); if ($current instanceof Collection) $current = $ids->modelKeys();
$records = $this->formatSyncList($ids); $records = $this->formatSyncList($ids);
$detach = array_diff($current, array_keys($records)); $detach = array_diff($current, array_keys($records));
// We need to make sure we pass a clean array, so that it is not interpreted // We need to make sure we pass a clean array, so that it is not interpreted
// as an associative array. // as an associative array.
$detach = array_values($detach); $detach = array_values($detach);
// Next, we will take the differences of the currents and given IDs and detach // Next, we will take the differences of the currents and given IDs and detach
// all of the entities that exist in the "current" array but are not in the // all of the entities that exist in the "current" array but are not in the
// the array of the IDs given to the method which will complete the sync. // the array of the IDs given to the method which will complete the sync.
if ($detaching and count($detach) > 0) if ($detaching and count($detach) > 0)
{ {
$this->detach($detach); $this->detach($detach);
$changes['detached'] = (array) array_map(function($v) { return (int) $v; }, $detach); $changes['detached'] = (array) array_map(function ($v) { return (int) $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
// touching until after the entire operation is complete so we don't fire a // touching until after the entire operation is complete so we don't fire a
// ton of touch operations until we are totally done syncing the records. // ton of touch operations until we are totally done syncing the records.
$changes = array_merge( $changes = array_merge(
$changes, $this->attachNew($records, $current, false) $changes, $this->attachNew($records, $current, false)
); );
if (count($changes['attached']) || count($changes['updated'])) if (count($changes['attached']) || count($changes['updated']))
{ {
$this->touchIfTouching(); $this->touchIfTouching();
} }
return $changes; return $changes;
} }
/** /**
* Update an existing pivot record on the table. * Update an existing pivot record on the table.
* *
* @param mixed $id * @param mixed $id
* @param array $attributes * @param array $attributes
* @param bool $touch * @param bool $touch
* @return void * @return void
*/ */
public function updateExistingPivot($id, array $attributes, $touch = true) public function updateExistingPivot($id, array $attributes, $touch = true)
{ {
// Do nothing, we have no pivot table. // Do nothing, we have no pivot table.
} }
/** /**
* Attach a model to the parent. * Attach a model to the parent.
* *
* @param mixed $id * @param mixed $id
* @param array $attributes * @param array $attributes
* @param bool $touch * @param bool $touch
* @return void * @return void
*/ */
public function attach($id, array $attributes = array(), $touch = true) public function attach($id, array $attributes = array(), $touch = true)
{ {
if ($id instanceof Model) if ($id instanceof Model)
{ {
$model = $id; $model = $id;
$id = $model->getKey(); $id = $model->getKey();
// Attach the new parent id to the related model. // Attach the new parent id to the related model.
$model->push($this->foreignKey, $this->parent->getKey(), true); $model->push($this->foreignKey, $this->parent->getKey(), true);
} }
else else
{ {
$query = $this->newRelatedQuery(); $query = $this->newRelatedQuery();
$query->whereIn($this->related->getKeyName(), (array) $id); $query->whereIn($this->related->getKeyName(), (array) $id);
// Attach the new parent id to the related model. // Attach the new parent id to the related model.
$query->push($this->foreignKey, $this->parent->getKey(), true); $query->push($this->foreignKey, $this->parent->getKey(), true);
} }
// Attach the new ids to the parent model. // Attach the new ids to the parent model.
$this->parent->push($this->otherKey, (array) $id, true); $this->parent->push($this->otherKey, (array) $id, true);
if ($touch) $this->touchIfTouching(); if ($touch) $this->touchIfTouching();
} }
/** /**
* Detach models from the relationship. * Detach models from the relationship.
* *
* @param int|array $ids * @param int|array $ids
* @param bool $touch * @param bool $touch
* @return int * @return int
*/ */
public function detach($ids = array(), $touch = true) public function detach($ids = array(), $touch = true)
{ {
if ($ids instanceof Model) $ids = (array) $ids->getKey(); if ($ids instanceof Model) $ids = (array) $ids->getKey();
$query = $this->newRelatedQuery(); $query = $this->newRelatedQuery();
// If associated IDs were passed to the method we will only delete those // If associated IDs were passed to the method we will only delete those
// associations, otherwise all of the association ties will be broken. // associations, otherwise all of the association ties will be broken.
// We'll return the numbers of affected rows when we do the deletes. // We'll return the numbers of affected rows when we do the deletes.
$ids = (array) $ids; $ids = (array) $ids;
// Detach all ids from the parent model. // Detach all ids from the parent model.
$this->parent->pull($this->otherKey, $ids); $this->parent->pull($this->otherKey, $ids);
// Prepare the query to select all related objects. // Prepare the query to select all related objects.
if (count($ids) > 0) if (count($ids) > 0)
{ {
$query->whereIn($this->related->getKeyName(), $ids); $query->whereIn($this->related->getKeyName(), $ids);
} }
// Remove the relation to the parent. // Remove the relation to the parent.
$query->pull($this->foreignKey, $this->parent->getKey()); $query->pull($this->foreignKey, $this->parent->getKey());
if ($touch) $this->touchIfTouching(); if ($touch) $this->touchIfTouching();
return count($ids); return count($ids);
} }
/** /**
* Build model dictionary keyed by the relation's foreign key. * Build model dictionary keyed by the relation's foreign key.
* *
* @param \Illuminate\Database\Eloquent\Collection $results * @param \Illuminate\Database\Eloquent\Collection $results
* @return array * @return array
*/ */
protected function buildDictionary(Collection $results) protected function buildDictionary(Collection $results)
{ {
$foreign = $this->foreignKey; $foreign = $this->foreignKey;
// First we will build a dictionary of child models keyed by the foreign key // First we will build a dictionary of child models keyed by the foreign key
// of the relation so that we will easily and quickly match them to their // of the relation so that we will easily and quickly match them to their
// parents without having a possibly slow inner loops for every models. // parents without having a possibly slow inner loops for every models.
$dictionary = array(); $dictionary = array();
foreach ($results as $result) foreach ($results as $result)
{ {
foreach ($result->$foreign as $item) foreach ($result->$foreign as $item)
{ {
$dictionary[$item][] = $result; $dictionary[$item][] = $result;
} }
} }
return $dictionary; return $dictionary;
} }
/** /**
* Create a new query builder for the related model. * Create a new query builder for the related model.
* *
* @return \Illuminate\Database\Query\Builder * @return \Illuminate\Database\Query\Builder
*/ */
protected function newPivotQuery() protected function newPivotQuery()
{ {
return $this->newRelatedQuery(); return $this->newRelatedQuery();
} }
/** /**
* Create a new query builder for the related model. * Create a new query builder for the related model.
* *
* @return \Illuminate\Database\Query\Builder * @return \Illuminate\Database\Query\Builder
*/ */
public function newRelatedQuery() public function newRelatedQuery()
{ {
return $this->related->newQuery(); return $this->related->newQuery();
} }
/** /**
* Get the fully qualified foreign key for the relation. * Get the fully qualified foreign key for the relation.
* *
* @return string * @return string
*/ */
public function getForeignKey() public function getForeignKey()
{ {
return $this->foreignKey; return $this->foreignKey;
} }
} }
...@@ -286,7 +286,7 @@ class EmbedsMany extends EmbedsOneOrMany { ...@@ -286,7 +286,7 @@ class EmbedsMany extends EmbedsOneOrMany {
$sliced = array_slice($results, $start, $perPage); $sliced = array_slice($results, $start, $perPage);
return new LengthAwarePaginator($sliced, $total, $perPage, $page, [ return new LengthAwarePaginator($sliced, $total, $perPage, $page, [
'path' => Paginator::resolveCurrentPath() 'path' => Paginator::resolveCurrentPath(),
]); ]);
} }
......
...@@ -2,8 +2,6 @@ ...@@ -2,8 +2,6 @@
use MongoId; use MongoId;
use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Relations\Relation;
class EmbedsOne extends EmbedsOneOrMany { class EmbedsOne extends EmbedsOneOrMany {
......
...@@ -124,10 +124,10 @@ abstract class EmbedsOneOrMany extends Relation { ...@@ -124,10 +124,10 @@ abstract class EmbedsOneOrMany extends Relation {
} }
/** /**
* Shorthand to get the results of the relationship. * Shorthand to get the results of the relationship.
* *
* @return Jenssegers\Mongodb\Eloquent\Collection * @return Jenssegers\Mongodb\Eloquent\Collection
*/ */
public function get() public function get()
{ {
return $this->getResults(); return $this->getResults();
...@@ -208,7 +208,7 @@ abstract class EmbedsOneOrMany extends Relation { ...@@ -208,7 +208,7 @@ abstract class EmbedsOneOrMany extends Relation {
} }
/** /**
* Transform single ID, single Model or array of Models into an array of IDs * Transform single ID, single Model or array of Models into an array of IDs.
* *
* @param mixed $ids * @param mixed $ids
* @return array * @return array
...@@ -305,7 +305,7 @@ abstract class EmbedsOneOrMany extends Relation { ...@@ -305,7 +305,7 @@ abstract class EmbedsOneOrMany extends Relation {
*/ */
protected function toModel($attributes = array()) protected function toModel($attributes = array())
{ {
if (is_null($attributes)) return null; if (is_null($attributes)) return;
$model = $this->related->newFromBuilder((array) $attributes); $model = $this->related->newFromBuilder((array) $attributes);
......
<?php namespace Jenssegers\Mongodb\Relations; <?php namespace Jenssegers\Mongodb\Relations;
use Illuminate\Database\Eloquent\Builder; use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Relations\HasMany as EloquentHasMany; use Illuminate\Database\Eloquent\Relations\HasMany as EloquentHasMany;
class HasMany extends EloquentHasMany { class HasMany extends EloquentHasMany {
......
<?php namespace Jenssegers\Mongodb\Relations; <?php namespace Jenssegers\Mongodb\Relations;
use Illuminate\Database\Eloquent\Builder; use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Relations\HasOne as EloquentHasOne; use Illuminate\Database\Eloquent\Relations\HasOne as EloquentHasOne;
class HasOne extends EloquentHasOne { class HasOne extends EloquentHasOne {
......
<?php namespace Jenssegers\Mongodb\Relations; <?php namespace Jenssegers\Mongodb\Relations;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Relations\MorphTo as EloquentMorphTo; use Illuminate\Database\Eloquent\Relations\MorphTo as EloquentMorphTo;
class MorphTo extends EloquentMorphTo { class MorphTo extends EloquentMorphTo {
/** /**
* Set the base constraints on the relation query. * Set the base constraints on the relation query.
* *
* @return void * @return void
*/ */
public function addConstraints() public function addConstraints()
{ {
if (static::$constraints) if (static::$constraints)
{ {
// For belongs to relationships, which are essentially the inverse of has one // For belongs to relationships, which are essentially the inverse of has one
// or has many relationships, we need to actually query on the primary key // or has many relationships, we need to actually query on the primary key
// of the related models matching on the foreign key that's on a parent. // of the related models matching on the foreign key that's on a parent.
$this->query->where($this->otherKey, '=', $this->parent->{$this->foreignKey}); $this->query->where($this->otherKey, '=', $this->parent->{$this->foreignKey});
} }
} }
} }
...@@ -5,232 +5,232 @@ use Illuminate\Database\Connection; ...@@ -5,232 +5,232 @@ use Illuminate\Database\Connection;
class Blueprint extends \Illuminate\Database\Schema\Blueprint { class Blueprint extends \Illuminate\Database\Schema\Blueprint {
/** /**
* The MongoConnection object for this blueprint. * The MongoConnection object for this blueprint.
* *
* @var MongoConnection * @var MongoConnection
*/ */
protected $connection; protected $connection;
/** /**
* The MongoCollection object for this blueprint. * The MongoCollection object for this blueprint.
* *
* @var MongoCollection * @var MongoCollection
*/ */
protected $collection; protected $collection;
/** /**
* Fluent columns * Fluent columns.
* *
* @var array * @var array
*/ */
protected $columns = array(); protected $columns = array();
/** /**
* Create a new schema blueprint. * Create a new schema blueprint.
* *
* @param string $table * @param string $table
* @param Closure $callback * @param Closure $callback
* @return void * @return void
*/ */
public function __construct(Connection $connection, $collection) public function __construct(Connection $connection, $collection)
{ {
$this->connection = $connection; $this->connection = $connection;
$this->collection = $connection->getCollection($collection); $this->collection = $connection->getCollection($collection);
} }
/** /**
* Specify an index for the collection. * Specify an index for the collection.
* *
* @param string|array $columns * @param string|array $columns
* @param array $options * @param array $options
* @return Blueprint * @return Blueprint
*/ */
public function index($columns = null, $options = array()) public function index($columns = null, $options = array())
{ {
$columns = $this->fluent($columns); $columns = $this->fluent($columns);
// Columns are passed as a default array. // Columns are passed as a default array.
if (is_array($columns) && is_int(key($columns))) if (is_array($columns) && is_int(key($columns)))
{ {
// Transform the columns to the required array format. // Transform the columns to the required array format.
$transform = array(); $transform = array();
foreach ($columns as $column) foreach ($columns as $column)
{ {
$transform[$column] = 1; $transform[$column] = 1;
} }
$columns = $transform; $columns = $transform;
} }
$this->collection->ensureIndex($columns, $options); $this->collection->ensureIndex($columns, $options);
return $this; return $this;
} }
/** /**
* Indicate that the given index should be dropped. * Indicate that the given index should be dropped.
* *
* @param string|array $columns * @param string|array $columns
* @return Blueprint * @return Blueprint
*/ */
public function dropIndex($columns = null) public function dropIndex($columns = null)
{ {
$columns = $this->fluent($columns); $columns = $this->fluent($columns);
// Columns are passed as a default array. // Columns are passed as a default array.
if (is_array($columns) && is_int(key($columns))) if (is_array($columns) && is_int(key($columns)))
{ {
// Transform the columns to the required array format. // Transform the columns to the required array format.
$transform = array(); $transform = array();
foreach ($columns as $column) foreach ($columns as $column)
{ {
$transform[$column] = 1; $transform[$column] = 1;
} }
$columns = $transform; $columns = $transform;
} }
$this->collection->deleteIndex($columns); $this->collection->deleteIndex($columns);
return $this; return $this;
} }
/** /**
* Specify a unique index for the collection. * Specify a unique index for the collection.
* *
* @param string|array $columns * @param string|array $columns
* @return Blueprint * @return Blueprint
*/ */
public function unique($columns = null, $name = null) public function unique($columns = null, $name = null)
{ {
$columns = $this->fluent($columns); $columns = $this->fluent($columns);
$this->index($columns, array('unique' => true)); $this->index($columns, array('unique' => true));
return $this; return $this;
} }
/** /**
* Specify a non blocking index for the collection. * Specify a non blocking index for the collection.
* *
* @param string|array $columns * @param string|array $columns
* @return Blueprint * @return Blueprint
*/ */
public function background($columns = null) public function background($columns = null)
{ {
$columns = $this->fluent($columns); $columns = $this->fluent($columns);
$this->index($columns, array('background' => true)); $this->index($columns, array('background' => true));
return $this; return $this;
} }
/** /**
* Specify a sparse index for the collection. * Specify a sparse index for the collection.
* *
* @param string|array $columns * @param string|array $columns
* @return Blueprint * @return Blueprint
*/ */
public function sparse($columns = null) public function sparse($columns = null)
{ {
$columns = $this->fluent($columns); $columns = $this->fluent($columns);
$this->index($columns, array('sparse' => true)); $this->index($columns, array('sparse' => true));
return $this; return $this;
} }
/** /**
* Specify the number of seconds after wich a document should be considered expired based, * Specify the number of seconds after wich a document should be considered expired based,
* on the given single-field index containing a date. * on the given single-field index containing a date.
* *
* @param string|array $columns * @param string|array $columns
* @param int $seconds * @param int $seconds
* @return Blueprint * @return Blueprint
*/ */
public function expire($columns, $seconds) public function expire($columns, $seconds)
{ {
$columns = $this->fluent($columns); $columns = $this->fluent($columns);
$this->index($columns, array('expireAfterSeconds' => $seconds)); $this->index($columns, array('expireAfterSeconds' => $seconds));
return $this; return $this;
} }
/** /**
* Indicate that the table needs to be created. * Indicate that the table needs to be created.
* *
* @return bool * @return bool
*/ */
public function create() public function create()
{ {
$collection = $this->collection->getName(); $collection = $this->collection->getName();
$db = $this->connection->getMongoDB(); $db = $this->connection->getMongoDB();
// Ensure the collection is created. // Ensure the collection is created.
$db->createCollection($collection); $db->createCollection($collection);
} }
/** /**
* Indicate that the collection should be dropped. * Indicate that the collection should be dropped.
* *
* @return bool * @return bool
*/ */
public function drop() public function drop()
{ {
$this->collection->drop(); $this->collection->drop();
} }
/** /**
* Add a new column to the blueprint. * Add a new column to the blueprint.
* *
* @param string $type * @param string $type
* @param string $name * @param string $name
* @param array $parameters * @param array $parameters
* @return Blueprint * @return Blueprint
*/ */
protected function addColumn($type, $name, array $parameters = array()) protected function addColumn($type, $name, array $parameters = array())
{ {
$this->fluent($name); $this->fluent($name);
return $this; return $this;
} }
/** /**
* Allow fluent columns * Allow fluent columns.
* *
* @param string|array $columns * @param string|array $columns
* @return string|array * @return string|array
*/ */
protected function fluent($columns = null) protected function fluent($columns = null)
{ {
if (is_null($columns)) if (is_null($columns))
{ {
return $this->columns; return $this->columns;
} }
else if (is_string($columns)) elseif (is_string($columns))
{ {
return $this->columns = array($columns); return $this->columns = array($columns);
} }
else else
{ {
return $this->columns = $columns; return $this->columns = $columns;
} }
} }
/** /**
* Allows the use of unsupported schema methods. * Allows the use of unsupported schema methods.
* *
* @return Blueprint * @return Blueprint
*/ */
public function __call($method, $args) public function __call($method, $args)
{ {
// Dummy. // Dummy.
return $this; return $this;
} }
} }
...@@ -2,114 +2,113 @@ ...@@ -2,114 +2,113 @@
use Closure; use Closure;
use Jenssegers\Mongodb\Connection; use Jenssegers\Mongodb\Connection;
use Jenssegers\Mongodb\Schema\Blueprint;
class Builder extends \Illuminate\Database\Schema\Builder { class Builder extends \Illuminate\Database\Schema\Builder {
/** /**
* Create a new database Schema manager. * Create a new database Schema manager.
* *
* @param Connection $connection * @param Connection $connection
*/ */
public function __construct(Connection $connection) public function __construct(Connection $connection)
{ {
$this->connection = $connection; $this->connection = $connection;
} }
/** /**
* Determine if the given collection exists. * Determine if the given collection exists.
* *
* @param string $collection * @param string $collection
* @return bool * @return bool
*/ */
public function hasCollection($collection) public function hasCollection($collection)
{ {
$db = $this->connection->getMongoDB(); $db = $this->connection->getMongoDB();
return in_array($collection, $db->getCollectionNames()); return in_array($collection, $db->getCollectionNames());
} }
/** /**
* Determine if the given collection exists. * Determine if the given collection exists.
* *
* @param string $collection * @param string $collection
* @return bool * @return bool
*/ */
public function hasTable($collection) public function hasTable($collection)
{ {
return $this->hasCollection($collection); return $this->hasCollection($collection);
} }
/** /**
* Modify a collection on the schema. * Modify a collection on the schema.
* *
* @param string $collection * @param string $collection
* @param Closure $callback * @param Closure $callback
* @return bool * @return bool
*/ */
public function collection($collection, Closure $callback) public function collection($collection, Closure $callback)
{ {
$blueprint = $this->createBlueprint($collection); $blueprint = $this->createBlueprint($collection);
if ($callback) if ($callback)
{ {
$callback($blueprint); $callback($blueprint);
} }
} }
/** /**
* Modify a collection on the schema. * Modify a collection on the schema.
* *
* @param string $collection * @param string $collection
* @param Closure $callback * @param Closure $callback
* @return bool * @return bool
*/ */
public function table($collection, Closure $callback) public function table($collection, Closure $callback)
{ {
return $this->collection($collection, $callback); return $this->collection($collection, $callback);
} }
/** /**
* Create a new collection on the schema. * Create a new collection on the schema.
* *
* @param string $collection * @param string $collection
* @param Closure $callback * @param Closure $callback
* @return bool * @return bool
*/ */
public function create($collection, Closure $callback = null) public function create($collection, Closure $callback = null)
{ {
$blueprint = $this->createBlueprint($collection); $blueprint = $this->createBlueprint($collection);
$blueprint->create(); $blueprint->create();
if ($callback) if ($callback)
{ {
$callback($blueprint); $callback($blueprint);
} }
} }
/** /**
* Drop a collection from the schema. * Drop a collection from the schema.
* *
* @param string $collection * @param string $collection
* @return bool * @return bool
*/ */
public function drop($collection) public function drop($collection)
{ {
$blueprint = $this->createBlueprint($collection); $blueprint = $this->createBlueprint($collection);
return $blueprint->drop(); return $blueprint->drop();
} }
/** /**
* Create a new Blueprint. * Create a new Blueprint.
* *
* @param string $collection * @param string $collection
* @return Schema\Blueprint * @return Schema\Blueprint
*/ */
protected function createBlueprint($collection, Closure $callback = null) protected function createBlueprint($collection, Closure $callback = null)
{ {
return new Blueprint($this->connection, $collection); return new Blueprint($this->connection, $collection);
} }
} }
...@@ -13,9 +13,9 @@ class AuthTest extends TestCase { ...@@ -13,9 +13,9 @@ class AuthTest extends TestCase {
public function testAuthAttempt() public function testAuthAttempt()
{ {
$user = User::create([ $user = User::create([
'name' => 'John Doe', 'name' => 'John Doe',
'email' => 'john@doe.com', 'email' => 'john@doe.com',
'password' => Hash::make('foobar') 'password' => Hash::make('foobar'),
]); ]);
$this->assertTrue(Auth::attempt(['email' => 'john@doe.com', 'password' => 'foobar'], true)); $this->assertTrue(Auth::attempt(['email' => 'john@doe.com', 'password' => 'foobar'], true));
...@@ -31,9 +31,9 @@ class AuthTest extends TestCase { ...@@ -31,9 +31,9 @@ class AuthTest extends TestCase {
$broker = new PasswordBroker($tokens, $users, $mailer, ''); $broker = new PasswordBroker($tokens, $users, $mailer, '');
$user = User::create([ $user = User::create([
'name' => 'John Doe', 'name' => 'John Doe',
'email' => 'john@doe.com', 'email' => 'john@doe.com',
'password' => Hash::make('foobar') 'password' => Hash::make('foobar'),
]); ]);
$mailer->shouldReceive('send')->once(); $mailer->shouldReceive('send')->once();
...@@ -46,13 +46,13 @@ class AuthTest extends TestCase { ...@@ -46,13 +46,13 @@ class AuthTest extends TestCase {
$this->assertInstanceOf('MongoDate', $reminder['created_at']); $this->assertInstanceOf('MongoDate', $reminder['created_at']);
$credentials = [ $credentials = [
'email' => 'john@doe.com', 'email' => 'john@doe.com',
'password' => 'foobar', 'password' => 'foobar',
'password_confirmation' => 'foobar', 'password_confirmation' => 'foobar',
'token' => $reminder['token'] 'token' => $reminder['token'],
]; ];
$response = $broker->reset($credentials, function($user, $password) $response = $broker->reset($credentials, function ($user, $password)
{ {
$user->password = bcrypt($password); $user->password = bcrypt($password);
$user->save(); $user->save();
......
...@@ -2,132 +2,132 @@ ...@@ -2,132 +2,132 @@
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', $connection); $this->assertInstanceOf('Jenssegers\Mongodb\Connection', $connection);
} }
public function testReconnect() public function testReconnect()
{ {
$c1 = DB::connection('mongodb'); $c1 = DB::connection('mongodb');
$c2 = DB::connection('mongodb'); $c2 = DB::connection('mongodb');
$this->assertEquals(spl_object_hash($c1), spl_object_hash($c2)); $this->assertEquals(spl_object_hash($c1), spl_object_hash($c2));
$c1 = DB::connection('mongodb'); $c1 = DB::connection('mongodb');
DB::purge('mongodb'); DB::purge('mongodb');
$c2 = DB::connection('mongodb'); $c2 = DB::connection('mongodb');
$this->assertNotEquals(spl_object_hash($c1), spl_object_hash($c2)); $this->assertNotEquals(spl_object_hash($c1), spl_object_hash($c2));
} }
public function testDb() public function testDb()
{ {
$connection = DB::connection('mongodb'); $connection = DB::connection('mongodb');
$this->assertInstanceOf('MongoDB', $connection->getMongoDB()); $this->assertInstanceOf('MongoDB', $connection->getMongoDB());
$connection = DB::connection('mongodb'); $connection = DB::connection('mongodb');
$this->assertInstanceOf('MongoClient', $connection->getMongoClient()); $this->assertInstanceOf('MongoClient', $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', $collection); $this->assertInstanceOf('Jenssegers\Mongodb\Collection', $collection);
$collection = DB::connection('mongodb')->collection('unittests'); $collection = DB::connection('mongodb')->collection('unittests');
$this->assertInstanceOf('Jenssegers\Mongodb\Query\Builder', $collection); $this->assertInstanceOf('Jenssegers\Mongodb\Query\Builder', $collection);
$collection = DB::connection('mongodb')->table('unittests'); $collection = DB::connection('mongodb')->table('unittests');
$this->assertInstanceOf('Jenssegers\Mongodb\Query\Builder', $collection); $this->assertInstanceOf('Jenssegers\Mongodb\Query\Builder', $collection);
} }
public function testDynamic() public function testDynamic()
{ {
$dbs = DB::connection('mongodb')->listCollections(); $dbs = DB::connection('mongodb')->listCollections();
$this->assertTrue(is_array($dbs)); $this->assertTrue(is_array($dbs));
} }
/*public function testMultipleConnections() /*public function testMultipleConnections()
{ {
global $app; global $app;
# Add fake host # Add fake host
$db = $app['config']['database.connections']['mongodb']; $db = $app['config']['database.connections']['mongodb'];
$db['host'] = array($db['host'], '1.2.3.4'); $db['host'] = array($db['host'], '1.2.3.4');
$connection = new Connection($db); $connection = new Connection($db);
$mongoclient = $connection->getMongoClient(); $mongoclient = $connection->getMongoClient();
$hosts = $mongoclient->getHosts(); $hosts = $mongoclient->getHosts();
$this->assertEquals(1, count($hosts)); $this->assertEquals(1, count($hosts));
}*/ }*/
public function testQueryLog() public function testQueryLog()
{ {
DB::enableQueryLog(); DB::enableQueryLog();
$this->assertEquals(0, count(DB::getQueryLog())); $this->assertEquals(0, count(DB::getQueryLog()));
DB::collection('items')->get(); DB::collection('items')->get();
$this->assertEquals(1, count(DB::getQueryLog())); $this->assertEquals(1, count(DB::getQueryLog()));
DB::collection('items')->insert(['name' => 'test']); DB::collection('items')->insert(['name' => 'test']);
$this->assertEquals(2, count(DB::getQueryLog())); $this->assertEquals(2, count(DB::getQueryLog()));
DB::collection('items')->count(); DB::collection('items')->count();
$this->assertEquals(3, count(DB::getQueryLog())); $this->assertEquals(3, count(DB::getQueryLog()));
DB::collection('items')->where('name', 'test')->update(['name' => 'test']); DB::collection('items')->where('name', 'test')->update(['name' => 'test']);
$this->assertEquals(4, count(DB::getQueryLog())); $this->assertEquals(4, count(DB::getQueryLog()));
DB::collection('items')->where('name', 'test')->delete(); DB::collection('items')->where('name', 'test')->delete();
$this->assertEquals(5, count(DB::getQueryLog())); $this->assertEquals(5, count(DB::getQueryLog()));
} }
public function testSchemaBuilder() public function testSchemaBuilder()
{ {
$schema = DB::connection('mongodb')->getSchemaBuilder(); $schema = DB::connection('mongodb')->getSchemaBuilder();
$this->assertInstanceOf('Jenssegers\Mongodb\Schema\Builder', $schema); $this->assertInstanceOf('Jenssegers\Mongodb\Schema\Builder', $schema);
} }
public function testDriverName() public function testDriverName()
{ {
$driver = DB::connection('mongodb')->getDriverName(); $driver = DB::connection('mongodb')->getDriverName();
$this->assertEquals('mongodb', $driver); $this->assertEquals('mongodb', $driver);
} }
public function testAuth() public function testAuth()
{ {
Config::set('database.connections.mongodb.username', 'foo'); Config::set('database.connections.mongodb.username', 'foo');
Config::set('database.connections.mongodb.password', 'bar'); Config::set('database.connections.mongodb.password', 'bar');
$host = Config::get('database.connections.mongodb.host'); $host = Config::get('database.connections.mongodb.host');
$port = Config::get('database.connections.mongodb.port', 27017); $port = Config::get('database.connections.mongodb.port', 27017);
$database = Config::get('database.connections.mongodb.database'); $database = Config::get('database.connections.mongodb.database');
$this->setExpectedExceptionRegExp('MongoConnectionException', "/Failed to connect to: $host:$port: Authentication failed on database '$database' with username 'foo': auth fail/"); $this->setExpectedExceptionRegExp('MongoConnectionException', "/Failed to connect to: $host:$port: Authentication failed on database '$database' with username 'foo': auth fail/");
$connection = DB::connection('mongodb'); $connection = DB::connection('mongodb');
} }
public function testCustomPort() public function testCustomPort()
{ {
$port = 27000; $port = 27000;
Config::set('database.connections.mongodb.port', $port); Config::set('database.connections.mongodb.port', $port);
$host = Config::get('database.connections.mongodb.host'); $host = Config::get('database.connections.mongodb.host');
$database = Config::get('database.connections.mongodb.database'); $database = Config::get('database.connections.mongodb.database');
$this->setExpectedException('MongoConnectionException', "Failed to connect to: $host:$port: Connection refused"); $this->setExpectedException('MongoConnectionException', "Failed to connect to: $host:$port: Connection refused");
$connection = DB::connection('mongodb'); $connection = DB::connection('mongodb');
} }
public function testHostWithPorts() public function testHostWithPorts()
{ {
$hosts = ['localhost:27001', 'localhost:27002']; $hosts = ['localhost:27001', 'localhost:27002'];
Config::set('database.connections.mongodb.port', 27000); Config::set('database.connections.mongodb.port', 27000);
Config::set('database.connections.mongodb.host', ['localhost:27001', 'localhost:27002']); Config::set('database.connections.mongodb.host', ['localhost:27001', 'localhost:27002']);
$database = Config::get('database.connections.mongodb.database'); $database = Config::get('database.connections.mongodb.database');
$this->setExpectedException('MongoConnectionException', "Failed to connect to: " . $hosts[0] . ": Connection refused; Failed to connect to: " . $hosts[1] . ": Connection refused"); $this->setExpectedException('MongoConnectionException', "Failed to connect to: " . $hosts[0] . ": Connection refused; Failed to connect to: " . $hosts[1] . ": Connection refused");
$connection = DB::connection('mongodb'); $connection = DB::connection('mongodb');
} }
} }
...@@ -2,488 +2,488 @@ ...@@ -2,488 +2,488 @@
class ModelTest extends TestCase { class ModelTest extends TestCase {
public function tearDown() public function tearDown()
{ {
User::truncate(); User::truncate();
Soft::truncate(); Soft::truncate();
Book::truncate(); Book::truncate();
Item::truncate(); Item::truncate();
} }
public function testNewModel() public function testNewModel()
{ {
$user = new User; $user = new User;
$this->assertInstanceOf('Jenssegers\Mongodb\Model', $user); $this->assertInstanceOf('Jenssegers\Mongodb\Model', $user);
$this->assertInstanceOf('Jenssegers\Mongodb\Connection', $user->getConnection()); $this->assertInstanceOf('Jenssegers\Mongodb\Connection', $user->getConnection());
$this->assertEquals(false, $user->exists); $this->assertEquals(false, $user->exists);
$this->assertEquals('users', $user->getTable()); $this->assertEquals('users', $user->getTable());
$this->assertEquals('_id', $user->getKeyName()); $this->assertEquals('_id', $user->getKeyName());
} }
public function testInsert() public function testInsert()
{ {
$user = new User; $user = new User;
$user->name = 'John Doe'; $user->name = 'John Doe';
$user->title = 'admin'; $user->title = 'admin';
$user->age = 35; $user->age = 35;
$user->save(); $user->save();
$this->assertEquals(true, $user->exists); $this->assertEquals(true, $user->exists);
$this->assertEquals(1, User::count()); $this->assertEquals(1, User::count());
$this->assertTrue(isset($user->_id)); $this->assertTrue(isset($user->_id));
$this->assertTrue(is_string($user->_id)); $this->assertTrue(is_string($user->_id));
$this->assertNotEquals('', (string) $user->_id); $this->assertNotEquals('', (string) $user->_id);
$this->assertNotEquals(0, strlen((string) $user->_id)); $this->assertNotEquals(0, strlen((string) $user->_id));
$this->assertInstanceOf('Carbon\Carbon', $user->created_at); $this->assertInstanceOf('Carbon\Carbon', $user->created_at);
$raw = $user->getAttributes(); $raw = $user->getAttributes();
$this->assertInstanceOf('MongoId', $raw['_id']); $this->assertInstanceOf('MongoId', $raw['_id']);
$this->assertEquals('John Doe', $user->name); $this->assertEquals('John Doe', $user->name);
$this->assertEquals(35, $user->age); $this->assertEquals(35, $user->age);
} }
public function testUpdate() public function testUpdate()
{ {
$user = new User; $user = new User;
$user->name = 'John Doe'; $user->name = 'John Doe';
$user->title = 'admin'; $user->title = 'admin';
$user->age = 35; $user->age = 35;
$user->save(); $user->save();
$raw = $user->getAttributes(); $raw = $user->getAttributes();
$this->assertInstanceOf('MongoId', $raw['_id']); $this->assertInstanceOf('MongoId', $raw['_id']);
$check = User::find($user->_id); $check = User::find($user->_id);
$check->age = 36; $check->age = 36;
$check->save(); $check->save();
$this->assertEquals(true, $check->exists); $this->assertEquals(true, $check->exists);
$this->assertInstanceOf('Carbon\Carbon', $check->created_at); $this->assertInstanceOf('Carbon\Carbon', $check->created_at);
$this->assertInstanceOf('Carbon\Carbon', $check->updated_at); $this->assertInstanceOf('Carbon\Carbon', $check->updated_at);
$this->assertEquals(1, User::count()); $this->assertEquals(1, User::count());
$this->assertEquals('John Doe', $check->name); $this->assertEquals('John Doe', $check->name);
$this->assertEquals(36, $check->age); $this->assertEquals(36, $check->age);
$user->update(['age' => 20]); $user->update(['age' => 20]);
$raw = $user->getAttributes(); $raw = $user->getAttributes();
$this->assertInstanceOf('MongoId', $raw['_id']); $this->assertInstanceOf('MongoId', $raw['_id']);
$check = User::find($user->_id); $check = User::find($user->_id);
$this->assertEquals(20, $check->age); $this->assertEquals(20, $check->age);
} }
public function testManualStringId() public function testManualStringId()
{ {
$user = new User; $user = new User;
$user->_id = '4af9f23d8ead0e1d32000000'; $user->_id = '4af9f23d8ead0e1d32000000';
$user->name = 'John Doe'; $user->name = 'John Doe';
$user->title = 'admin'; $user->title = 'admin';
$user->age = 35; $user->age = 35;
$user->save(); $user->save();
$this->assertEquals(true, $user->exists); $this->assertEquals(true, $user->exists);
$this->assertEquals('4af9f23d8ead0e1d32000000', $user->_id); $this->assertEquals('4af9f23d8ead0e1d32000000', $user->_id);
$raw = $user->getAttributes(); $raw = $user->getAttributes();
$this->assertInstanceOf('MongoId', $raw['_id']); $this->assertInstanceOf('MongoId', $raw['_id']);
$user = new User; $user = new User;
$user->_id = 'customId'; $user->_id = 'customId';
$user->name = 'John Doe'; $user->name = 'John Doe';
$user->title = 'admin'; $user->title = 'admin';
$user->age = 35; $user->age = 35;
$user->save(); $user->save();
$this->assertEquals(true, $user->exists); $this->assertEquals(true, $user->exists);
$this->assertEquals('customId', $user->_id); $this->assertEquals('customId', $user->_id);
$raw = $user->getAttributes(); $raw = $user->getAttributes();
$this->assertInternalType('string', $raw['_id']); $this->assertInternalType('string', $raw['_id']);
} }
public function testManualIntId() public function testManualIntId()
{ {
$user = new User; $user = new User;
$user->_id = 1; $user->_id = 1;
$user->name = 'John Doe'; $user->name = 'John Doe';
$user->title = 'admin'; $user->title = 'admin';
$user->age = 35; $user->age = 35;
$user->save(); $user->save();
$this->assertEquals(true, $user->exists); $this->assertEquals(true, $user->exists);
$this->assertEquals(1, $user->_id); $this->assertEquals(1, $user->_id);
$raw = $user->getAttributes(); $raw = $user->getAttributes();
$this->assertInternalType('integer', $raw['_id']); $this->assertInternalType('integer', $raw['_id']);
} }
public function testDelete() public function testDelete()
{ {
$user = new User; $user = new User;
$user->name = 'John Doe'; $user->name = 'John Doe';
$user->title = 'admin'; $user->title = 'admin';
$user->age = 35; $user->age = 35;
$user->save(); $user->save();
$this->assertEquals(true, $user->exists); $this->assertEquals(true, $user->exists);
$this->assertEquals(1, User::count()); $this->assertEquals(1, User::count());
$user->delete(); $user->delete();
$this->assertEquals(0, User::count()); $this->assertEquals(0, User::count());
} }
public function testAll() public function testAll()
{ {
$user = new User; $user = new User;
$user->name = 'John Doe'; $user->name = 'John Doe';
$user->title = 'admin'; $user->title = 'admin';
$user->age = 35; $user->age = 35;
$user->save(); $user->save();
$user = new User; $user = new User;
$user->name = 'Jane Doe'; $user->name = 'Jane Doe';
$user->title = 'user'; $user->title = 'user';
$user->age = 32; $user->age = 32;
$user->save(); $user->save();
$all = User::all(); $all = User::all();
$this->assertEquals(2, count($all)); $this->assertEquals(2, count($all));
$this->assertContains('John Doe', $all->lists('name')); $this->assertContains('John Doe', $all->lists('name'));
$this->assertContains('Jane Doe', $all->lists('name')); $this->assertContains('Jane Doe', $all->lists('name'));
} }
public function testFind() public function testFind()
{ {
$user = new User; $user = new User;
$user->name = 'John Doe'; $user->name = 'John Doe';
$user->title = 'admin'; $user->title = 'admin';
$user->age = 35; $user->age = 35;
$user->save(); $user->save();
$check = User::find($user->_id); $check = User::find($user->_id);
$this->assertInstanceOf('Jenssegers\Mongodb\Model', $check); $this->assertInstanceOf('Jenssegers\Mongodb\Model', $check);
$this->assertEquals(true, $check->exists); $this->assertEquals(true, $check->exists);
$this->assertEquals($user->_id, $check->_id); $this->assertEquals($user->_id, $check->_id);
$this->assertEquals('John Doe', $check->name); $this->assertEquals('John Doe', $check->name);
$this->assertEquals(35, $check->age); $this->assertEquals(35, $check->age);
} }
public function testGet() public function testGet()
{ {
User::insert([ User::insert([
['name' => 'John Doe'], ['name' => 'John Doe'],
['name' => 'Jane Doe'] ['name' => 'Jane Doe'],
]); ]);
$users = User::get(); $users = User::get();
$this->assertEquals(2, count($users)); $this->assertEquals(2, count($users));
$this->assertInstanceOf('Illuminate\Database\Eloquent\Collection', $users); $this->assertInstanceOf('Illuminate\Database\Eloquent\Collection', $users);
$this->assertInstanceOf('Jenssegers\Mongodb\Model', $users[0]); $this->assertInstanceOf('Jenssegers\Mongodb\Model', $users[0]);
} }
public function testFirst() public function testFirst()
{ {
User::insert([ User::insert([
['name' => 'John Doe'], ['name' => 'John Doe'],
['name' => 'Jane Doe'] ['name' => 'Jane Doe'],
]); ]);
$user = User::first(); $user = User::first();
$this->assertInstanceOf('Jenssegers\Mongodb\Model', $user); $this->assertInstanceOf('Jenssegers\Mongodb\Model', $user);
$this->assertEquals('John Doe', $user->name); $this->assertEquals('John Doe', $user->name);
} }
public function testNoDocument() public function testNoDocument()
{ {
$items = Item::where('name', 'nothing')->get(); $items = Item::where('name', 'nothing')->get();
$this->assertInstanceOf('Illuminate\Database\Eloquent\Collection', $items); $this->assertInstanceOf('Illuminate\Database\Eloquent\Collection', $items);
$this->assertEquals(0, $items->count()); $this->assertEquals(0, $items->count());
$item =Item::where('name', 'nothing')->first(); $item = Item::where('name', 'nothing')->first();
$this->assertEquals(null, $item); $this->assertEquals(null, $item);
$item = Item::find('51c33d8981fec6813e00000a'); $item = Item::find('51c33d8981fec6813e00000a');
$this->assertEquals(null, $item); $this->assertEquals(null, $item);
} }
public function testFindOrfail() public function testFindOrfail()
{ {
$this->setExpectedException('Illuminate\Database\Eloquent\ModelNotFoundException'); $this->setExpectedException('Illuminate\Database\Eloquent\ModelNotFoundException');
User::findOrfail('51c33d8981fec6813e00000a'); User::findOrfail('51c33d8981fec6813e00000a');
} }
public function testCreate() public function testCreate()
{ {
$user = User::create(['name' => 'Jane Poe']); $user = User::create(['name' => 'Jane Poe']);
$this->assertInstanceOf('Jenssegers\Mongodb\Model', $user); $this->assertInstanceOf('Jenssegers\Mongodb\Model', $user);
$this->assertEquals(true, $user->exists); $this->assertEquals(true, $user->exists);
$this->assertEquals('Jane Poe', $user->name); $this->assertEquals('Jane Poe', $user->name);
$check = User::where('name', 'Jane Poe')->first(); $check = User::where('name', 'Jane Poe')->first();
$this->assertEquals($user, $check); $this->assertEquals($user, $check);
} }
public function testDestroy() public function testDestroy()
{ {
$user = new User; $user = new User;
$user->name = 'John Doe'; $user->name = 'John Doe';
$user->title = 'admin'; $user->title = 'admin';
$user->age = 35; $user->age = 35;
$user->save(); $user->save();
User::destroy((string) $user->_id); User::destroy((string) $user->_id);
$this->assertEquals(0, User::count()); $this->assertEquals(0, User::count());
} }
public function testTouch() public function testTouch()
{ {
$user = new User; $user = new User;
$user->name = 'John Doe'; $user->name = 'John Doe';
$user->title = 'admin'; $user->title = 'admin';
$user->age = 35; $user->age = 35;
$user->save(); $user->save();
$old = $user->updated_at; $old = $user->updated_at;
sleep(1); sleep(1);
$user->touch(); $user->touch();
$check = User::find($user->_id); $check = User::find($user->_id);
$this->assertNotEquals($old, $check->updated_at); $this->assertNotEquals($old, $check->updated_at);
} }
public function testSoftDelete() public function testSoftDelete()
{ {
Soft::create(['name' => 'John Doe']); Soft::create(['name' => 'John Doe']);
Soft::create(['name' => 'Jane Doe']); Soft::create(['name' => 'Jane Doe']);
$this->assertEquals(2, Soft::count()); $this->assertEquals(2, Soft::count());
$user = Soft::where('name', 'John Doe')->first(); $user = Soft::where('name', 'John Doe')->first();
$this->assertEquals(true, $user->exists); $this->assertEquals(true, $user->exists);
$this->assertEquals(false, $user->trashed()); $this->assertEquals(false, $user->trashed());
$this->assertNull($user->deleted_at); $this->assertNull($user->deleted_at);
$user->delete(); $user->delete();
$this->assertEquals(true, $user->trashed()); $this->assertEquals(true, $user->trashed());
$this->assertNotNull($user->deleted_at); $this->assertNotNull($user->deleted_at);
$user = Soft::where('name', 'John Doe')->first(); $user = Soft::where('name', 'John Doe')->first();
$this->assertNull($user); $this->assertNull($user);
$this->assertEquals(1, Soft::count()); $this->assertEquals(1, Soft::count());
$this->assertEquals(2, Soft::withTrashed()->count()); $this->assertEquals(2, Soft::withTrashed()->count());
$user = Soft::withTrashed()->where('name', 'John Doe')->first(); $user = Soft::withTrashed()->where('name', 'John Doe')->first();
$this->assertNotNull($user); $this->assertNotNull($user);
$this->assertInstanceOf('Carbon\Carbon', $user->deleted_at); $this->assertInstanceOf('Carbon\Carbon', $user->deleted_at);
$this->assertEquals(true, $user->trashed()); $this->assertEquals(true, $user->trashed());
$user->restore(); $user->restore();
$this->assertEquals(2, Soft::count()); $this->assertEquals(2, Soft::count());
} }
public function testPrimaryKey() public function testPrimaryKey()
{ {
$user = new User; $user = new User;
$this->assertEquals('_id', $user->getKeyName()); $this->assertEquals('_id', $user->getKeyName());
$book = new Book; $book = new Book;
$this->assertEquals('title', $book->getKeyName()); $this->assertEquals('title', $book->getKeyName());
$book->title = 'A Game of Thrones'; $book->title = 'A Game of Thrones';
$book->author = 'George R. R. Martin'; $book->author = 'George R. R. Martin';
$book->save(); $book->save();
$this->assertEquals('A Game of Thrones', $book->getKey()); $this->assertEquals('A Game of Thrones', $book->getKey());
$check = Book::find('A Game of Thrones'); $check = Book::find('A Game of Thrones');
$this->assertEquals('title', $check->getKeyName()); $this->assertEquals('title', $check->getKeyName());
$this->assertEquals('A Game of Thrones', $check->getKey()); $this->assertEquals('A Game of Thrones', $check->getKey());
$this->assertEquals('A Game of Thrones', $check->title); $this->assertEquals('A Game of Thrones', $check->title);
} }
public function testScope() public function testScope()
{ {
Item::insert([ Item::insert([
['name' => 'knife', 'type' => 'sharp'], ['name' => 'knife', 'type' => 'sharp'],
['name' => 'spoon', 'type' => 'round'] ['name' => 'spoon', 'type' => 'round'],
]); ]);
$sharp = Item::sharp()->get(); $sharp = Item::sharp()->get();
$this->assertEquals(1, $sharp->count()); $this->assertEquals(1, $sharp->count());
} }
public function testToArray() public function testToArray()
{ {
$item = Item::create(['name' => 'fork', 'type' => 'sharp']); $item = Item::create(['name' => 'fork', 'type' => 'sharp']);
$array = $item->toArray(); $array = $item->toArray();
$keys = array_keys($array); sort($keys); $keys = array_keys($array); sort($keys);
$this->assertEquals(['_id', 'created_at', 'name', 'type', 'updated_at'], $keys); $this->assertEquals(['_id', 'created_at', 'name', 'type', 'updated_at'], $keys);
$this->assertTrue(is_string($array['created_at'])); $this->assertTrue(is_string($array['created_at']));
$this->assertTrue(is_string($array['updated_at'])); $this->assertTrue(is_string($array['updated_at']));
$this->assertTrue(is_string($array['_id'])); $this->assertTrue(is_string($array['_id']));
} }
public function testUnset() public function testUnset()
{ {
$user1 = User::create(['name' => 'John Doe', 'note1' => 'ABC', 'note2' => 'DEF']); $user1 = User::create(['name' => 'John Doe', 'note1' => 'ABC', 'note2' => 'DEF']);
$user2 = User::create(['name' => 'Jane Doe', 'note1' => 'ABC', 'note2' => 'DEF']); $user2 = User::create(['name' => 'Jane Doe', 'note1' => 'ABC', 'note2' => 'DEF']);
$user1->unset('note1'); $user1->unset('note1');
$this->assertFalse(isset($user1->note1)); $this->assertFalse(isset($user1->note1));
$this->assertTrue(isset($user1->note2)); $this->assertTrue(isset($user1->note2));
$this->assertTrue(isset($user2->note1)); $this->assertTrue(isset($user2->note1));
$this->assertTrue(isset($user2->note2)); $this->assertTrue(isset($user2->note2));
// Re-fetch to be sure // Re-fetch to be sure
$user1 = User::find($user1->_id); $user1 = User::find($user1->_id);
$user2 = User::find($user2->_id); $user2 = User::find($user2->_id);
$this->assertFalse(isset($user1->note1)); $this->assertFalse(isset($user1->note1));
$this->assertTrue(isset($user1->note2)); $this->assertTrue(isset($user1->note2));
$this->assertTrue(isset($user2->note1)); $this->assertTrue(isset($user2->note1));
$this->assertTrue(isset($user2->note2)); $this->assertTrue(isset($user2->note2));
$user2->unset(['note1', 'note2']); $user2->unset(['note1', 'note2']);
$this->assertFalse(isset($user2->note1)); $this->assertFalse(isset($user2->note1));
$this->assertFalse(isset($user2->note2)); $this->assertFalse(isset($user2->note2));
} }
public function testDates() public function testDates()
{ {
$birthday = new DateTime('1980/1/1'); $birthday = new DateTime('1980/1/1');
$user = User::create(['name' => 'John Doe', 'birthday' => $birthday]); $user = User::create(['name' => 'John Doe', 'birthday' => $birthday]);
$this->assertInstanceOf('Carbon\Carbon', $user->birthday); $this->assertInstanceOf('Carbon\Carbon', $user->birthday);
$check = User::find($user->_id); $check = User::find($user->_id);
$this->assertInstanceOf('Carbon\Carbon', $check->birthday); $this->assertInstanceOf('Carbon\Carbon', $check->birthday);
$this->assertEquals($user->birthday, $check->birthday); $this->assertEquals($user->birthday, $check->birthday);
$user = User::where('birthday', '>', new DateTime('1975/1/1'))->first(); $user = User::where('birthday', '>', new DateTime('1975/1/1'))->first();
$this->assertEquals('John Doe', $user->name); $this->assertEquals('John Doe', $user->name);
// test custom date format for json output // test custom date format for json output
$json = $user->toArray(); $json = $user->toArray();
$this->assertEquals((string) $user->birthday, $json['birthday']); $this->assertEquals((string) $user->birthday, $json['birthday']);
$this->assertEquals((string) $user->created_at, $json['created_at']); $this->assertEquals((string) $user->created_at, $json['created_at']);
// test default date format for json output // test default date format for json output
$item = Item::create(['name' => 'sword']); $item = Item::create(['name' => 'sword']);
$json = $item->toArray(); $json = $item->toArray();
$this->assertEquals($item->created_at->format('Y-m-d H:i:s'), $json['created_at']); $this->assertEquals($item->created_at->format('Y-m-d H:i:s'), $json['created_at']);
$user = User::create(['name' => 'Jane Doe', 'birthday' => time()]); $user = User::create(['name' => 'Jane Doe', 'birthday' => time()]);
$this->assertInstanceOf('Carbon\Carbon', $user->birthday); $this->assertInstanceOf('Carbon\Carbon', $user->birthday);
$user = User::create(['name' => 'Jane Doe', 'birthday' => 'Monday 8th of August 2005 03:12:46 PM']); $user = User::create(['name' => 'Jane Doe', 'birthday' => 'Monday 8th of August 2005 03:12:46 PM']);
$this->assertInstanceOf('Carbon\Carbon', $user->birthday); $this->assertInstanceOf('Carbon\Carbon', $user->birthday);
$user = User::create(['name' => 'Jane Doe', 'birthday' => '2005-08-08']); $user = User::create(['name' => 'Jane Doe', 'birthday' => '2005-08-08']);
$this->assertInstanceOf('Carbon\Carbon', $user->birthday); $this->assertInstanceOf('Carbon\Carbon', $user->birthday);
$user = User::create(['name' => 'Jane Doe', 'entry' => ['date' => '2005-08-08']]); $user = User::create(['name' => 'Jane Doe', 'entry' => ['date' => '2005-08-08']]);
$this->assertInstanceOf('Carbon\Carbon', $user->getAttribute('entry.date')); $this->assertInstanceOf('Carbon\Carbon', $user->getAttribute('entry.date'));
$user->setAttribute('entry.date', new DateTime); $user->setAttribute('entry.date', new DateTime);
$this->assertInstanceOf('Carbon\Carbon', $user->getAttribute('entry.date')); $this->assertInstanceOf('Carbon\Carbon', $user->getAttribute('entry.date'));
} }
public function testIdAttribute() public function testIdAttribute()
{ {
$user = User::create(['name' => 'John Doe']); $user = User::create(['name' => 'John Doe']);
$this->assertEquals($user->id, $user->_id); $this->assertEquals($user->id, $user->_id);
$user = User::create(['id' => 'custom_id', 'name' => 'John Doe']); $user = User::create(['id' => 'custom_id', 'name' => 'John Doe']);
$this->assertNotEquals($user->id, $user->_id); $this->assertNotEquals($user->id, $user->_id);
} }
public function testPushPull() public function testPushPull()
{ {
$user = User::create(['name' => 'John Doe']); $user = User::create(['name' => 'John Doe']);
$user->push('tags', 'tag1'); $user->push('tags', 'tag1');
$user->push('tags', ['tag1', 'tag2']); $user->push('tags', ['tag1', 'tag2']);
$user->push('tags', 'tag2', true); $user->push('tags', 'tag2', true);
$this->assertEquals(['tag1', 'tag1', 'tag2'], $user->tags); $this->assertEquals(['tag1', 'tag1', 'tag2'], $user->tags);
$user = User::where('_id', $user->_id)->first(); $user = User::where('_id', $user->_id)->first();
$this->assertEquals(['tag1', 'tag1', 'tag2'], $user->tags); $this->assertEquals(['tag1', 'tag1', 'tag2'], $user->tags);
$user->pull('tags', 'tag1'); $user->pull('tags', 'tag1');
$this->assertEquals(['tag2'], $user->tags); $this->assertEquals(['tag2'], $user->tags);
$user = User::where('_id', $user->_id)->first(); $user = User::where('_id', $user->_id)->first();
$this->assertEquals(['tag2'], $user->tags); $this->assertEquals(['tag2'], $user->tags);
$user->push('tags', 'tag3'); $user->push('tags', 'tag3');
$user->pull('tags', ['tag2', 'tag3']); $user->pull('tags', ['tag2', 'tag3']);
$this->assertEquals([], $user->tags); $this->assertEquals([], $user->tags);
$user = User::where('_id', $user->_id)->first(); $user = User::where('_id', $user->_id)->first();
$this->assertEquals([], $user->tags); $this->assertEquals([], $user->tags);
} }
public function testRaw() public function testRaw()
{ {
User::create(['name' => 'John Doe', 'age' => 35]); User::create(['name' => 'John Doe', 'age' => 35]);
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($collection) $users = User::raw(function ($collection)
{ {
return $collection->find(['age' => 35]); return $collection->find(['age' => 35]);
}); });
$this->assertInstanceOf('Illuminate\Database\Eloquent\Collection', $users); $this->assertInstanceOf('Illuminate\Database\Eloquent\Collection', $users);
$this->assertInstanceOf('Jenssegers\Mongodb\Model', $users[0]); $this->assertInstanceOf('Jenssegers\Mongodb\Model', $users[0]);
$user = User::raw(function($collection) $user = User::raw(function ($collection)
{ {
return $collection->findOne(['age' => 35]); return $collection->findOne(['age' => 35]);
}); });
$this->assertInstanceOf('Jenssegers\Mongodb\Model', $user); $this->assertInstanceOf('Jenssegers\Mongodb\Model', $user);
$count = User::raw(function($collection) $count = User::raw(function ($collection)
{ {
return $collection->count(); return $collection->count();
}); });
$this->assertEquals(3, $count); $this->assertEquals(3, $count);
$result = User::raw(function($collection) $result = User::raw(function ($collection)
{ {
return $collection->insert(['name' => 'Yvonne Yoe', 'age' => 35]); return $collection->insert(['name' => 'Yvonne Yoe', 'age' => 35]);
}); });
$this->assertTrue(is_array($result)); $this->assertTrue(is_array($result));
} }
public function testDotNotation() public function testDotNotation()
{ {
$user = User::create([ $user = User::create([
'name' => 'John Doe', 'name' => 'John Doe',
'address' => [ 'address' => [
'city' => 'Paris', 'city' => 'Paris',
'country' => 'France', 'country' => 'France',
] ],
]); ]);
$this->assertEquals('Paris', $user->getAttribute('address.city')); $this->assertEquals('Paris', $user->getAttribute('address.city'));
$this->assertEquals('Paris', $user['address.city']); $this->assertEquals('Paris', $user['address.city']);
$this->assertEquals('Paris', $user->{'address.city'}); $this->assertEquals('Paris', $user->{'address.city'});
} }
} }
...@@ -2,643 +2,643 @@ ...@@ -2,643 +2,643 @@
class QueryBuilderTest extends TestCase { class QueryBuilderTest extends TestCase {
public function tearDown() public function tearDown()
{ {
DB::collection('users')->truncate(); DB::collection('users')->truncate();
DB::collection('items')->truncate(); DB::collection('items')->truncate();
} }
public function testCollection() public function testCollection()
{ {
$this->assertInstanceOf('Jenssegers\Mongodb\Query\Builder', DB::collection('users')); $this->assertInstanceOf('Jenssegers\Mongodb\Query\Builder', DB::collection('users'));
} }
public function testGet() public function testGet()
{ {
$users = DB::collection('users')->get(); $users = DB::collection('users')->get();
$this->assertEquals(0, count($users)); $this->assertEquals(0, count($users));
DB::collection('users')->insert(['name' => 'John Doe']); DB::collection('users')->insert(['name' => 'John Doe']);
$users = DB::collection('users')->get(); $users = DB::collection('users')->get();
$this->assertEquals(1, count($users)); $this->assertEquals(1, count($users));
} }
public function testNoDocument() public function testNoDocument()
{ {
$items = DB::collection('items')->where('name', 'nothing')->get(); $items = DB::collection('items')->where('name', 'nothing')->get();
$this->assertEquals([], $items); $this->assertEquals([], $items);
$item = DB::collection('items')->where('name', 'nothing')->first(); $item = DB::collection('items')->where('name', 'nothing')->first();
$this->assertEquals(null, $item); $this->assertEquals(null, $item);
$item = DB::collection('items')->where('_id', '51c33d8981fec6813e00000a')->first(); $item = DB::collection('items')->where('_id', '51c33d8981fec6813e00000a')->first();
$this->assertEquals(null, $item); $this->assertEquals(null, $item);
} }
public function testInsert() public function testInsert()
{ {
DB::collection('users')->insert([ DB::collection('users')->insert([
'tags' => ['tag1', 'tag2'], 'tags' => ['tag1', 'tag2'],
'name' => 'John Doe', 'name' => 'John Doe',
]); ]);
$users = DB::collection('users')->get(); $users = DB::collection('users')->get();
$this->assertEquals(1, count($users)); $this->assertEquals(1, count($users));
$user = $users[0]; $user = $users[0];
$this->assertEquals('John Doe', $user['name']); $this->assertEquals('John Doe', $user['name']);
$this->assertTrue(is_array($user['tags'])); $this->assertTrue(is_array($user['tags']));
} }
public function testInsertGetId() public function testInsertGetId()
{ {
$id = DB::collection('users')->insertGetId(['name' => 'John Doe']); $id = DB::collection('users')->insertGetId(['name' => 'John Doe']);
$this->assertInstanceOf('MongoId', $id); $this->assertInstanceOf('MongoId', $id);
} }
public function testBatchInsert() public function testBatchInsert()
{ {
DB::collection('users')->insert([ DB::collection('users')->insert([
[ [
'tags' => ['tag1', 'tag2'], 'tags' => ['tag1', 'tag2'],
'name' => 'Jane Doe', 'name' => 'Jane Doe',
], ],
[ [
'tags' => ['tag3'], 'tags' => ['tag3'],
'name' => 'John Doe', 'name' => 'John Doe',
], ],
]); ]);
$users = DB::collection('users')->get(); $users = DB::collection('users')->get();
$this->assertEquals(2, count($users)); $this->assertEquals(2, count($users));
$this->assertTrue(is_array($users[0]['tags'])); $this->assertTrue(is_array($users[0]['tags']));
} }
public function testFind() public function testFind()
{ {
$id = DB::collection('users')->insertGetId(['name' => 'John Doe']); $id = DB::collection('users')->insertGetId(['name' => 'John Doe']);
$user = DB::collection('users')->find($id); $user = DB::collection('users')->find($id);
$this->assertEquals('John Doe', $user['name']); $this->assertEquals('John Doe', $user['name']);
} }
public function testFindNull() public function testFindNull()
{ {
$user = DB::collection('users')->find(null); $user = DB::collection('users')->find(null);
$this->assertEquals(null, $user); $this->assertEquals(null, $user);
} }
public function testCount() public function testCount()
{ {
DB::collection('users')->insert([ DB::collection('users')->insert([
['name' => 'Jane Doe'], ['name' => 'Jane Doe'],
['name' => 'John Doe'] ['name' => 'John Doe'],
]); ]);
$this->assertEquals(2, DB::collection('users')->count()); $this->assertEquals(2, DB::collection('users')->count());
} }
public function testUpdate() public function testUpdate()
{ {
DB::collection('users')->insert([ DB::collection('users')->insert([
['name' => 'Jane Doe', 'age' => 20], ['name' => 'Jane Doe', 'age' => 20],
['name' => 'John Doe', 'age' => 21] ['name' => 'John Doe', 'age' => 21],
]); ]);
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(); $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();
$this->assertEquals(100, $john['age']); $this->assertEquals(100, $john['age']);
$this->assertEquals(20, $jane['age']); $this->assertEquals(20, $jane['age']);
} }
public function testDelete() public function testDelete()
{ {
DB::collection('users')->insert([ DB::collection('users')->insert([
['name' => 'Jane Doe', 'age' => 20], ['name' => 'Jane Doe', 'age' => 20],
['name' => 'John Doe', 'age' => 25] ['name' => 'John Doe', 'age' => 25],
]); ]);
DB::collection('users')->where('age', '<', 10)->delete(); DB::collection('users')->where('age', '<', 10)->delete();
$this->assertEquals(2, DB::collection('users')->count()); $this->assertEquals(2, DB::collection('users')->count());
DB::collection('users')->where('age', '<', 25)->delete(); DB::collection('users')->where('age', '<', 25)->delete();
$this->assertEquals(1, DB::collection('users')->count()); $this->assertEquals(1, DB::collection('users')->count());
} }
public function testTruncate() public function testTruncate()
{ {
DB::collection('users')->insert(['name' => 'John Doe']); DB::collection('users')->insert(['name' => 'John Doe']);
DB::collection('users')->truncate(); DB::collection('users')->truncate();
$this->assertEquals(0, DB::collection('users')->count()); $this->assertEquals(0, DB::collection('users')->count());
} }
public function testSubKey() public function testSubKey()
{ {
DB::collection('users')->insert([ DB::collection('users')->insert([
[ [
'name' => 'John Doe', 'name' => 'John Doe',
'address' => ['country' => 'Belgium', 'city' => 'Ghent'] 'address' => ['country' => 'Belgium', 'city' => 'Ghent'],
], ],
[ [
'name' => 'Jane Doe', 'name' => 'Jane Doe',
'address' => ['country' => 'France', 'city' => 'Paris'] 'address' => ['country' => 'France', 'city' => 'Paris'],
] ],
]); ]);
$users = DB::collection('users')->where('address.country', 'Belgium')->get(); $users = DB::collection('users')->where('address.country', 'Belgium')->get();
$this->assertEquals(1, count($users)); $this->assertEquals(1, count($users));
$this->assertEquals('John Doe', $users[0]['name']); $this->assertEquals('John Doe', $users[0]['name']);
} }
public function testInArray() public function testInArray()
{ {
DB::collection('items')->insert([ DB::collection('items')->insert([
[ [
'tags' => ['tag1', 'tag2', 'tag3', 'tag4'] 'tags' => ['tag1', 'tag2', 'tag3', 'tag4'],
], ],
[ [
'tags' => ['tag2'] 'tags' => ['tag2'],
] ],
]); ]);
$items = DB::collection('items')->where('tags', 'tag2')->get(); $items = DB::collection('items')->where('tags', 'tag2')->get();
$this->assertEquals(2, count($items)); $this->assertEquals(2, count($items));
$items = DB::collection('items')->where('tags', 'tag1')->get(); $items = DB::collection('items')->where('tags', 'tag1')->get();
$this->assertEquals(1, count($items)); $this->assertEquals(1, count($items));
} }
public function testRaw() public function testRaw()
{ {
DB::collection('users')->insert([ DB::collection('users')->insert([
['name' => 'Jane Doe', 'age' => 20], ['name' => 'Jane Doe', 'age' => 20],
['name' => 'John Doe', 'age' => 25] ['name' => 'John Doe', 'age' => 25],
]); ]);
$cursor = DB::collection('users')->raw(function($collection) $cursor = DB::collection('users')->raw(function ($collection)
{ {
return $collection->find(['age' => 20]); return $collection->find(['age' => 20]);
}); });
$this->assertInstanceOf('MongoCursor', $cursor); $this->assertInstanceOf('MongoCursor', $cursor);
$this->assertEquals(1, $cursor->count()); $this->assertEquals(1, $cursor->count());
$collection = DB::collection('users')->raw(); $collection = DB::collection('users')->raw();
$this->assertInstanceOf('Jenssegers\Mongodb\Collection', $collection); $this->assertInstanceOf('Jenssegers\Mongodb\Collection', $collection);
$collection = User::raw(); $collection = User::raw();
$this->assertInstanceOf('Jenssegers\Mongodb\Collection', $collection); $this->assertInstanceOf('Jenssegers\Mongodb\Collection', $collection);
$results = DB::collection('users')->whereRaw(['age' => 20])->get(); $results = DB::collection('users')->whereRaw(['age' => 20])->get();
$this->assertEquals(1, count($results)); $this->assertEquals(1, count($results));
$this->assertEquals('Jane Doe', $results[0]['name']); $this->assertEquals('Jane Doe', $results[0]['name']);
} }
public function testPush() public function testPush()
{ {
$id = DB::collection('users')->insertGetId([ $id = DB::collection('users')->insertGetId([
'name' => 'John Doe', 'name' => 'John Doe',
'tags' => [], 'tags' => [],
'messages' => [], 'messages' => [],
]); ]);
DB::collection('users')->where('_id', $id)->push('tags', 'tag1'); DB::collection('users')->where('_id', $id)->push('tags', 'tag1');
$user = DB::collection('users')->find($id); $user = DB::collection('users')->find($id);
$this->assertTrue(is_array($user['tags'])); $this->assertTrue(is_array($user['tags']));
$this->assertEquals(1, count($user['tags'])); $this->assertEquals(1, count($user['tags']));
$this->assertEquals('tag1', $user['tags'][0]); $this->assertEquals('tag1', $user['tags'][0]);
DB::collection('users')->where('_id', $id)->push('tags', 'tag2'); DB::collection('users')->where('_id', $id)->push('tags', 'tag2');
$user = DB::collection('users')->find($id); $user = DB::collection('users')->find($id);
$this->assertEquals(2, count($user['tags'])); $this->assertEquals(2, count($user['tags']));
$this->assertEquals('tag2', $user['tags'][1]); $this->assertEquals('tag2', $user['tags'][1]);
// Add duplicate // Add duplicate
DB::collection('users')->where('_id', $id)->push('tags', 'tag2'); DB::collection('users')->where('_id', $id)->push('tags', 'tag2');
$user = DB::collection('users')->find($id); $user = DB::collection('users')->find($id);
$this->assertEquals(3, count($user['tags'])); $this->assertEquals(3, count($user['tags']));
// Add unique // Add unique
DB::collection('users')->where('_id', $id)->push('tags', 'tag1', true); DB::collection('users')->where('_id', $id)->push('tags', 'tag1', true);
$user = DB::collection('users')->find($id); $user = DB::collection('users')->find($id);
$this->assertEquals(3, count($user['tags'])); $this->assertEquals(3, count($user['tags']));
$message = ['from' => 'Jane', 'body' => 'Hi John']; $message = ['from' => 'Jane', 'body' => 'Hi John'];
DB::collection('users')->where('_id', $id)->push('messages', $message); DB::collection('users')->where('_id', $id)->push('messages', $message);
$user = DB::collection('users')->find($id); $user = DB::collection('users')->find($id);
$this->assertTrue(is_array($user['messages'])); $this->assertTrue(is_array($user['messages']));
$this->assertEquals(1, count($user['messages'])); $this->assertEquals(1, count($user['messages']));
$this->assertEquals($message, $user['messages'][0]); $this->assertEquals($message, $user['messages'][0]);
// Raw // Raw
DB::collection('users')->where('_id', $id)->push(['tags' => 'tag3', 'messages' => ['from' => 'Mark', 'body' => 'Hi John']]); DB::collection('users')->where('_id', $id)->push(['tags' => 'tag3', 'messages' => ['from' => 'Mark', 'body' => 'Hi John']]);
$user = DB::collection('users')->find($id); $user = DB::collection('users')->find($id);
$this->assertEquals(4, count($user['tags'])); $this->assertEquals(4, count($user['tags']));
$this->assertEquals(2, count($user['messages'])); $this->assertEquals(2, count($user['messages']));
DB::collection('users')->where('_id', $id)->push(['messages' => ['date' => new MongoDate(), 'body' => 'Hi John']]); DB::collection('users')->where('_id', $id)->push(['messages' => ['date' => new MongoDate(), 'body' => 'Hi John']]);
$user = DB::collection('users')->find($id); $user = DB::collection('users')->find($id);
$this->assertEquals(3, count($user['messages'])); $this->assertEquals(3, count($user['messages']));
} }
public function testPull() public function testPull()
{ {
$message1 = ['from' => 'Jane', 'body' => 'Hi John']; $message1 = ['from' => 'Jane', 'body' => 'Hi John'];
$message2 = ['from' => 'Mark', 'body' => 'Hi John']; $message2 = ['from' => 'Mark', 'body' => 'Hi John'];
$id = DB::collection('users')->insertGetId([ $id = DB::collection('users')->insertGetId([
'name' => 'John Doe', 'name' => 'John Doe',
'tags' => ['tag1', 'tag2', 'tag3', 'tag4'], 'tags' => ['tag1', 'tag2', 'tag3', 'tag4'],
'messages' => [$message1, $message2] 'messages' => [$message1, $message2],
]); ]);
DB::collection('users')->where('_id', $id)->pull('tags', 'tag3'); DB::collection('users')->where('_id', $id)->pull('tags', 'tag3');
$user = DB::collection('users')->find($id); $user = DB::collection('users')->find($id);
$this->assertTrue(is_array($user['tags'])); $this->assertTrue(is_array($user['tags']));
$this->assertEquals(3, count($user['tags'])); $this->assertEquals(3, count($user['tags']));
$this->assertEquals('tag4', $user['tags'][2]); $this->assertEquals('tag4', $user['tags'][2]);
DB::collection('users')->where('_id', $id)->pull('messages', $message1); DB::collection('users')->where('_id', $id)->pull('messages', $message1);
$user = DB::collection('users')->find($id); $user = DB::collection('users')->find($id);
$this->assertTrue(is_array($user['messages'])); $this->assertTrue(is_array($user['messages']));
$this->assertEquals(1, count($user['messages'])); $this->assertEquals(1, count($user['messages']));
// Raw // Raw
DB::collection('users')->where('_id', $id)->pull(['tags' => 'tag2', 'messages' => $message2]); DB::collection('users')->where('_id', $id)->pull(['tags' => 'tag2', 'messages' => $message2]);
$user = DB::collection('users')->find($id); $user = DB::collection('users')->find($id);
$this->assertEquals(2, count($user['tags'])); $this->assertEquals(2, count($user['tags']));
$this->assertEquals(0, count($user['messages'])); $this->assertEquals(0, count($user['messages']));
} }
public function testDistinct() public function testDistinct()
{ {
DB::collection('items')->insert([ DB::collection('items')->insert([
['name' => 'knife', 'type' => 'sharp',], ['name' => 'knife', 'type' => 'sharp'],
['name' => 'fork', 'type' => 'sharp'], ['name' => 'fork', 'type' => 'sharp'],
['name' => 'spoon', 'type' => 'round'], ['name' => 'spoon', 'type' => 'round'],
['name' => 'spoon', 'type' => 'round'] ['name' => 'spoon', 'type' => 'round'],
]); ]);
$items = DB::collection('items')->distinct('name')->get(); sort($items); $items = DB::collection('items')->distinct('name')->get(); sort($items);
$this->assertEquals(3, count($items)); $this->assertEquals(3, count($items));
$this->assertEquals(['fork', 'knife', 'spoon'], $items); $this->assertEquals(['fork', 'knife', 'spoon'], $items);
$types = DB::collection('items')->distinct('type')->get(); sort($types); $types = DB::collection('items')->distinct('type')->get(); sort($types);
$this->assertEquals(2, count($types)); $this->assertEquals(2, count($types));
$this->assertEquals(['round', 'sharp'], $types); $this->assertEquals(['round', 'sharp'], $types);
} }
public function testCustomId() public function testCustomId()
{ {
DB::collection('items')->insert([ DB::collection('items')->insert([
['_id' => 'knife', 'type' => 'sharp', 'amount' => 34], ['_id' => 'knife', 'type' => 'sharp', 'amount' => 34],
['_id' => 'fork', 'type' => 'sharp', 'amount' => 20], ['_id' => 'fork', 'type' => 'sharp', 'amount' => 20],
['_id' => 'spoon', 'type' => 'round', 'amount' => 3] ['_id' => 'spoon', 'type' => 'round', 'amount' => 3],
]); ]);
$item = DB::collection('items')->find('knife'); $item = DB::collection('items')->find('knife');
$this->assertEquals('knife', $item['_id']); $this->assertEquals('knife', $item['_id']);
$item = DB::collection('items')->where('_id', 'fork')->first(); $item = DB::collection('items')->where('_id', 'fork')->first();
$this->assertEquals('fork', $item['_id']); $this->assertEquals('fork', $item['_id']);
DB::collection('users')->insert([ DB::collection('users')->insert([
['_id' => 1, 'name' => 'Jane Doe'], ['_id' => 1, 'name' => 'Jane Doe'],
['_id' => 2, 'name' => 'John Doe'] ['_id' => 2, 'name' => 'John Doe'],
]); ]);
$item = DB::collection('users')->find(1); $item = DB::collection('users')->find(1);
$this->assertEquals(1, $item['_id']); $this->assertEquals(1, $item['_id']);
} }
public function testTake() public function testTake()
{ {
DB::collection('items')->insert([ DB::collection('items')->insert([
['name' => 'knife', 'type' => 'sharp', 'amount' => 34], ['name' => 'knife', 'type' => 'sharp', 'amount' => 34],
['name' => 'fork', 'type' => 'sharp', 'amount' => 20], ['name' => 'fork', 'type' => 'sharp', 'amount' => 20],
['name' => 'spoon', 'type' => 'round', 'amount' => 3], ['name' => 'spoon', 'type' => 'round', 'amount' => 3],
['name' => 'spoon', 'type' => 'round', 'amount' => 14] ['name' => 'spoon', 'type' => 'round', 'amount' => 14],
]); ]);
$items = DB::collection('items')->orderBy('name')->take(2)->get(); $items = DB::collection('items')->orderBy('name')->take(2)->get();
$this->assertEquals(2, count($items)); $this->assertEquals(2, count($items));
$this->assertEquals('fork', $items[0]['name']); $this->assertEquals('fork', $items[0]['name']);
} }
public function testSkip() public function testSkip()
{ {
DB::collection('items')->insert([ DB::collection('items')->insert([
['name' => 'knife', 'type' => 'sharp', 'amount' => 34], ['name' => 'knife', 'type' => 'sharp', 'amount' => 34],
['name' => 'fork', 'type' => 'sharp', 'amount' => 20], ['name' => 'fork', 'type' => 'sharp', 'amount' => 20],
['name' => 'spoon', 'type' => 'round', 'amount' => 3], ['name' => 'spoon', 'type' => 'round', 'amount' => 3],
['name' => 'spoon', 'type' => 'round', 'amount' => 14] ['name' => 'spoon', 'type' => 'round', 'amount' => 14],
]); ]);
$items = DB::collection('items')->orderBy('name')->skip(2)->get(); $items = DB::collection('items')->orderBy('name')->skip(2)->get();
$this->assertEquals(2, count($items)); $this->assertEquals(2, count($items));
$this->assertEquals('spoon', $items[0]['name']); $this->assertEquals('spoon', $items[0]['name']);
} }
public function testPluck() public function testPluck()
{ {
DB::collection('users')->insert([ DB::collection('users')->insert([
['name' => 'Jane Doe', 'age' => 20], ['name' => 'Jane Doe', 'age' => 20],
['name' => 'John Doe', 'age' => 25] ['name' => 'John Doe', 'age' => 25],
]); ]);
$age = DB::collection('users')->where('name', 'John Doe')->pluck('age'); $age = DB::collection('users')->where('name', 'John Doe')->pluck('age');
$this->assertEquals(25, $age); $this->assertEquals(25, $age);
} }
public function testList() public function testList()
{ {
DB::collection('items')->insert([ DB::collection('items')->insert([
['name' => 'knife', 'type' => 'sharp', 'amount' => 34], ['name' => 'knife', 'type' => 'sharp', 'amount' => 34],
['name' => 'fork', 'type' => 'sharp', 'amount' => 20], ['name' => 'fork', 'type' => 'sharp', 'amount' => 20],
['name' => 'spoon', 'type' => 'round', 'amount' => 3], ['name' => 'spoon', 'type' => 'round', 'amount' => 3],
['name' => 'spoon', 'type' => 'round', 'amount' => 14] ['name' => 'spoon', 'type' => 'round', 'amount' => 14],
]); ]);
$list = DB::collection('items')->lists('name'); $list = DB::collection('items')->lists('name');
sort($list); sort($list);
$this->assertEquals(4, count($list)); $this->assertEquals(4, count($list));
$this->assertEquals(['fork', 'knife', 'spoon', 'spoon'], $list); $this->assertEquals(['fork', 'knife', 'spoon', 'spoon'], $list);
$list = DB::collection('items')->lists('type', 'name'); $list = DB::collection('items')->lists('type', 'name');
$this->assertEquals(3, count($list)); $this->assertEquals(3, count($list));
$this->assertEquals(['knife' => 'sharp', 'fork' => 'sharp', 'spoon' => 'round'], $list); $this->assertEquals(['knife' => 'sharp', 'fork' => 'sharp', 'spoon' => 'round'], $list);
$list = DB::collection('items')->lists('name', '_id'); $list = DB::collection('items')->lists('name', '_id');
$this->assertEquals(4, count($list)); $this->assertEquals(4, count($list));
$this->assertEquals(24, strlen(key($list))); $this->assertEquals(24, strlen(key($list)));
} }
public function testAggregate() public function testAggregate()
{ {
DB::collection('items')->insert([ DB::collection('items')->insert([
['name' => 'knife', 'type' => 'sharp', 'amount' => 34], ['name' => 'knife', 'type' => 'sharp', 'amount' => 34],
['name' => 'fork', 'type' => 'sharp', 'amount' => 20], ['name' => 'fork', 'type' => 'sharp', 'amount' => 20],
['name' => 'spoon', 'type' => 'round', 'amount' => 3], ['name' => 'spoon', 'type' => 'round', 'amount' => 3],
['name' => 'spoon', 'type' => 'round', 'amount' => 14] ['name' => 'spoon', 'type' => 'round', 'amount' => 14],
]); ]);
$this->assertEquals(71, DB::collection('items')->sum('amount')); $this->assertEquals(71, DB::collection('items')->sum('amount'));
$this->assertEquals(4, DB::collection('items')->count('amount')); $this->assertEquals(4, DB::collection('items')->count('amount'));
$this->assertEquals(3, DB::collection('items')->min('amount')); $this->assertEquals(3, DB::collection('items')->min('amount'));
$this->assertEquals(34, DB::collection('items')->max('amount')); $this->assertEquals(34, DB::collection('items')->max('amount'));
$this->assertEquals(17.75, DB::collection('items')->avg('amount')); $this->assertEquals(17.75, DB::collection('items')->avg('amount'));
$this->assertEquals(2, DB::collection('items')->where('name', 'spoon')->count('amount')); $this->assertEquals(2, DB::collection('items')->where('name', 'spoon')->count('amount'));
$this->assertEquals(14, DB::collection('items')->where('name', 'spoon')->max('amount')); $this->assertEquals(14, DB::collection('items')->where('name', 'spoon')->max('amount'));
} }
public function testSubdocumentAggregate() public function testSubdocumentAggregate()
{ {
DB::collection('items')->insert([ DB::collection('items')->insert([
['name' => 'knife', 'amount' => ['hidden' => 10, 'found' => 3]], ['name' => 'knife', 'amount' => ['hidden' => 10, 'found' => 3]],
['name' => 'fork', 'amount' => ['hidden' => 35, 'found' => 12]], ['name' => 'fork', 'amount' => ['hidden' => 35, 'found' => 12]],
['name' => 'spoon', 'amount' => ['hidden' => 14, 'found' => 21]], ['name' => 'spoon', 'amount' => ['hidden' => 14, 'found' => 21]],
['name' => 'spoon', 'amount' => ['hidden' => 6, 'found' => 4]] ['name' => 'spoon', 'amount' => ['hidden' => 6, 'found' => 4]],
]); ]);
$this->assertEquals(65, DB::collection('items')->sum('amount.hidden')); $this->assertEquals(65, DB::collection('items')->sum('amount.hidden'));
$this->assertEquals(4, DB::collection('items')->count('amount.hidden')); $this->assertEquals(4, DB::collection('items')->count('amount.hidden'));
$this->assertEquals(6, DB::collection('items')->min('amount.hidden')); $this->assertEquals(6, DB::collection('items')->min('amount.hidden'));
$this->assertEquals(35, DB::collection('items')->max('amount.hidden')); $this->assertEquals(35, DB::collection('items')->max('amount.hidden'));
$this->assertEquals(16.25, DB::collection('items')->avg('amount.hidden')); $this->assertEquals(16.25, DB::collection('items')->avg('amount.hidden'));
} }
public function testUpsert() public function testUpsert()
{ {
DB::collection('items')->where('name', 'knife') DB::collection('items')->where('name', 'knife')
->update( ->update(
['amount' => 1], ['amount' => 1],
['upsert' => true] ['upsert' => true]
); );
$this->assertEquals(1, DB::collection('items')->count()); $this->assertEquals(1, DB::collection('items')->count());
} }
public function testUnset() public function testUnset()
{ {
$id1 = DB::collection('users')->insertGetId(['name' => 'John Doe', 'note1' => 'ABC', 'note2' => 'DEF']); $id1 = DB::collection('users')->insertGetId(['name' => 'John Doe', 'note1' => 'ABC', 'note2' => 'DEF']);
$id2 = DB::collection('users')->insertGetId(['name' => 'Jane Doe', 'note1' => 'ABC', 'note2' => 'DEF']); $id2 = DB::collection('users')->insertGetId(['name' => 'Jane Doe', 'note1' => 'ABC', 'note2' => 'DEF']);
DB::collection('users')->where('name', 'John Doe')->unset('note1'); DB::collection('users')->where('name', 'John Doe')->unset('note1');
$user1 = DB::collection('users')->find($id1); $user1 = DB::collection('users')->find($id1);
$user2 = DB::collection('users')->find($id2); $user2 = DB::collection('users')->find($id2);
$this->assertFalse(isset($user1['note1'])); $this->assertFalse(isset($user1['note1']));
$this->assertTrue(isset($user1['note2'])); $this->assertTrue(isset($user1['note2']));
$this->assertTrue(isset($user2['note1'])); $this->assertTrue(isset($user2['note1']));
$this->assertTrue(isset($user2['note2'])); $this->assertTrue(isset($user2['note2']));
DB::collection('users')->where('name', 'Jane Doe')->unset(['note1', 'note2']); DB::collection('users')->where('name', 'Jane Doe')->unset(['note1', 'note2']);
$user2 = DB::collection('users')->find($id2); $user2 = DB::collection('users')->find($id2);
$this->assertFalse(isset($user2['note1'])); $this->assertFalse(isset($user2['note1']));
$this->assertFalse(isset($user2['note2'])); $this->assertFalse(isset($user2['note2']));
} }
public function testUpdateSubdocument() public function testUpdateSubdocument()
{ {
$id = DB::collection('users')->insertGetId(['name' => 'John Doe', 'address' => ['country' => 'Belgium']]); $id = DB::collection('users')->insertGetId(['name' => 'John Doe', 'address' => ['country' => 'Belgium']]);
DB::collection('users')->where('_id', $id)->update(['address.country' => 'England']); DB::collection('users')->where('_id', $id)->update(['address.country' => 'England']);
$check = DB::collection('users')->find($id); $check = DB::collection('users')->find($id);
$this->assertEquals('England', $check['address']['country']); $this->assertEquals('England', $check['address']['country']);
} }
public function testDates() public function testDates()
{ {
DB::collection('users')->insert([ DB::collection('users')->insert([
['name' => 'John Doe', 'birthday' => new MongoDate(strtotime("1980-01-01 00:00:00"))], ['name' => 'John Doe', 'birthday' => new MongoDate(strtotime("1980-01-01 00:00:00"))],
['name' => 'Jane Doe', 'birthday' => new MongoDate(strtotime("1981-01-01 00:00:00"))], ['name' => 'Jane Doe', 'birthday' => new MongoDate(strtotime("1981-01-01 00:00:00"))],
['name' => 'Robert Roe', 'birthday' => new MongoDate(strtotime("1982-01-01 00:00:00"))], ['name' => 'Robert Roe', 'birthday' => new MongoDate(strtotime("1982-01-01 00:00:00"))],
['name' => 'Mark Moe', 'birthday' => new MongoDate(strtotime("1983-01-01 00:00:00"))], ['name' => 'Mark Moe', 'birthday' => new MongoDate(strtotime("1983-01-01 00:00:00"))],
]); ]);
$user = DB::collection('users')->where('birthday', new MongoDate(strtotime("1980-01-01 00:00:00")))->first(); $user = DB::collection('users')->where('birthday', new MongoDate(strtotime("1980-01-01 00:00:00")))->first();
$this->assertEquals('John Doe', $user['name']); $this->assertEquals('John Doe', $user['name']);
$user = DB::collection('users')->where('birthday', '=', new DateTime("1980-01-01 00:00:00"))->first(); $user = DB::collection('users')->where('birthday', '=', new DateTime("1980-01-01 00:00:00"))->first();
$this->assertEquals('John Doe', $user['name']); $this->assertEquals('John Doe', $user['name']);
$start = new MongoDate(strtotime("1981-01-01 00:00:00")); $start = new MongoDate(strtotime("1981-01-01 00:00:00"));
$stop = new MongoDate(strtotime("1982-01-01 00:00:00")); $stop = new MongoDate(strtotime("1982-01-01 00:00:00"));
$users = DB::collection('users')->whereBetween('birthday', [$start, $stop])->get(); $users = DB::collection('users')->whereBetween('birthday', [$start, $stop])->get();
$this->assertEquals(2, count($users)); $this->assertEquals(2, count($users));
} }
public function testOperators() public function testOperators()
{ {
DB::collection('users')->insert([ DB::collection('users')->insert([
['name' => 'John Doe', 'age' => 30], ['name' => 'John Doe', 'age' => 30],
['name' => 'Jane Doe'], ['name' => 'Jane Doe'],
['name' => 'Robert Roe', 'age' => 'thirty-one'], ['name' => 'Robert Roe', 'age' => 'thirty-one'],
]); ]);
$results = DB::collection('users')->where('age', 'exists', true)->get(); $results = DB::collection('users')->where('age', 'exists', true)->get();
$this->assertEquals(2, count($results)); $this->assertEquals(2, count($results));
$resultsNames = [$results[0]['name'], $results[1]['name']]; $resultsNames = [$results[0]['name'], $results[1]['name']];
$this->assertContains('John Doe', $resultsNames); $this->assertContains('John Doe', $resultsNames);
$this->assertContains('Robert Roe', $resultsNames); $this->assertContains('Robert Roe', $resultsNames);
$results = DB::collection('users')->where('age', 'exists', false)->get(); $results = DB::collection('users')->where('age', 'exists', false)->get();
$this->assertEquals(1, count($results)); $this->assertEquals(1, count($results));
$this->assertEquals('Jane Doe', $results[0]['name']); $this->assertEquals('Jane Doe', $results[0]['name']);
$results = DB::collection('users')->where('age', 'type', 2)->get(); $results = DB::collection('users')->where('age', 'type', 2)->get();
$this->assertEquals(1, count($results)); $this->assertEquals(1, count($results));
$this->assertEquals('Robert Roe', $results[0]['name']); $this->assertEquals('Robert Roe', $results[0]['name']);
$results = DB::collection('users')->where('age', 'mod', [15, 0])->get(); $results = DB::collection('users')->where('age', 'mod', [15, 0])->get();
$this->assertEquals(1, count($results)); $this->assertEquals(1, count($results));
$this->assertEquals('John Doe', $results[0]['name']); $this->assertEquals('John Doe', $results[0]['name']);
$results = DB::collection('users')->where('age', 'mod', [29, 1])->get(); $results = DB::collection('users')->where('age', 'mod', [29, 1])->get();
$this->assertEquals(1, count($results)); $this->assertEquals(1, count($results));
$this->assertEquals('John Doe', $results[0]['name']); $this->assertEquals('John Doe', $results[0]['name']);
$results = DB::collection('users')->where('age', 'mod', [14, 0])->get(); $results = DB::collection('users')->where('age', 'mod', [14, 0])->get();
$this->assertEquals(0, count($results)); $this->assertEquals(0, count($results));
DB::collection('items')->insert([ DB::collection('items')->insert([
['name' => 'fork', 'tags' => ['sharp', 'pointy']], ['name' => 'fork', 'tags' => ['sharp', 'pointy']],
['name' => 'spork', 'tags' => ['sharp', 'pointy', 'round', 'bowl']], ['name' => 'spork', 'tags' => ['sharp', 'pointy', 'round', 'bowl']],
['name' => 'spoon', 'tags' => ['round', 'bowl']], ['name' => 'spoon', 'tags' => ['round', 'bowl']],
]); ]);
$results = DB::collection('items')->where('tags', 'all', ['sharp', 'pointy'])->get(); $results = DB::collection('items')->where('tags', 'all', ['sharp', 'pointy'])->get();
$this->assertEquals(2, count($results)); $this->assertEquals(2, count($results));
$results = DB::collection('items')->where('tags', 'all', ['sharp', 'round'])->get(); $results = DB::collection('items')->where('tags', 'all', ['sharp', 'round'])->get();
$this->assertEquals(1, count($results)); $this->assertEquals(1, count($results));
$results = DB::collection('items')->where('tags', 'size', 2)->get(); $results = DB::collection('items')->where('tags', 'size', 2)->get();
$this->assertEquals(2, count($results)); $this->assertEquals(2, count($results));
$results = DB::collection('items')->where('tags', '$size', 2)->get(); $results = DB::collection('items')->where('tags', '$size', 2)->get();
$this->assertEquals(2, count($results)); $this->assertEquals(2, count($results));
$results = DB::collection('items')->where('tags', 'size', 3)->get(); $results = DB::collection('items')->where('tags', 'size', 3)->get();
$this->assertEquals(0, count($results)); $this->assertEquals(0, count($results));
$results = DB::collection('items')->where('tags', 'size', 4)->get(); $results = DB::collection('items')->where('tags', 'size', 4)->get();
$this->assertEquals(1, count($results)); $this->assertEquals(1, count($results));
$regex = new MongoRegex("/.*doe/i"); $regex = new MongoRegex("/.*doe/i");
$results = DB::collection('users')->where('name', 'regex', $regex)->get(); $results = DB::collection('users')->where('name', 'regex', $regex)->get();
$this->assertEquals(2, count($results)); $this->assertEquals(2, count($results));
$regex = new MongoRegex("/.*doe/i"); $regex = new MongoRegex("/.*doe/i");
$results = DB::collection('users')->where('name', 'regexp', $regex)->get(); $results = DB::collection('users')->where('name', 'regexp', $regex)->get();
$this->assertEquals(2, count($results)); $this->assertEquals(2, count($results));
$results = DB::collection('users')->where('name', 'REGEX', $regex)->get(); $results = DB::collection('users')->where('name', 'REGEX', $regex)->get();
$this->assertEquals(2, count($results)); $this->assertEquals(2, count($results));
$results = DB::collection('users')->where('name', 'regexp', '/.*doe/i')->get(); $results = DB::collection('users')->where('name', 'regexp', '/.*doe/i')->get();
$this->assertEquals(2, count($results)); $this->assertEquals(2, count($results));
$results = DB::collection('users')->where('name', 'not regexp', '/.*doe/i')->get(); $results = DB::collection('users')->where('name', 'not regexp', '/.*doe/i')->get();
$this->assertEquals(1, count($results)); $this->assertEquals(1, count($results));
DB::collection('users')->insert([ DB::collection('users')->insert([
[ [
'name' => 'John Doe', 'name' => 'John Doe',
'addresses' => [ 'addresses' => [
['city' => 'Ghent'], ['city' => 'Ghent'],
['city' => 'Paris'] ['city' => 'Paris'],
] ],
], ],
[ [
'name' => 'Jane Doe', 'name' => 'Jane Doe',
'addresses' => [ 'addresses' => [
['city' => 'Brussels'], ['city' => 'Brussels'],
['city' => 'Paris'] ['city' => 'Paris'],
] ],
] ],
]); ]);
$users = DB::collection('users')->where('addresses', 'elemMatch', ['city' => 'Brussels'])->get(); $users = DB::collection('users')->where('addresses', 'elemMatch', ['city' => 'Brussels'])->get();
$this->assertEquals(1, count($users)); $this->assertEquals(1, count($users));
$this->assertEquals('Jane Doe', $users[0]['name']); $this->assertEquals('Jane Doe', $users[0]['name']);
} }
public function testIncrement() public function testIncrement()
{ {
DB::collection('users')->insert([ DB::collection('users')->insert([
['name' => 'John Doe', 'age' => 30, 'note' => 'adult'], ['name' => 'John Doe', 'age' => 30, 'note' => 'adult'],
['name' => 'Jane Doe', 'age' => 10, 'note' => 'minor'], ['name' => 'Jane Doe', 'age' => 10, 'note' => 'minor'],
['name' => 'Robert Roe', 'age' => null], ['name' => 'Robert Roe', 'age' => null],
['name' => 'Mark Moe'], ['name' => 'Mark Moe'],
]); ]);
$user = DB::collection('users')->where('name', 'John Doe')->first(); $user = DB::collection('users')->where('name', 'John Doe')->first();
$this->assertEquals(30, $user['age']); $this->assertEquals(30, $user['age']);
DB::collection('users')->where('name', 'John Doe')->increment('age'); DB::collection('users')->where('name', 'John Doe')->increment('age');
$user = DB::collection('users')->where('name', 'John Doe')->first(); $user = DB::collection('users')->where('name', 'John Doe')->first();
$this->assertEquals(31, $user['age']); $this->assertEquals(31, $user['age']);
DB::collection('users')->where('name', 'John Doe')->decrement('age'); DB::collection('users')->where('name', 'John Doe')->decrement('age');
$user = DB::collection('users')->where('name', 'John Doe')->first(); $user = DB::collection('users')->where('name', 'John Doe')->first();
$this->assertEquals(30, $user['age']); $this->assertEquals(30, $user['age']);
DB::collection('users')->where('name', 'John Doe')->increment('age', 5); DB::collection('users')->where('name', 'John Doe')->increment('age', 5);
$user = DB::collection('users')->where('name', 'John Doe')->first(); $user = DB::collection('users')->where('name', 'John Doe')->first();
$this->assertEquals(35, $user['age']); $this->assertEquals(35, $user['age']);
DB::collection('users')->where('name', 'John Doe')->decrement('age', 5); DB::collection('users')->where('name', 'John Doe')->decrement('age', 5);
$user = DB::collection('users')->where('name', 'John Doe')->first(); $user = DB::collection('users')->where('name', 'John Doe')->first();
$this->assertEquals(30, $user['age']); $this->assertEquals(30, $user['age']);
DB::collection('users')->where('name', 'Jane Doe')->increment('age', 10, ['note' => 'adult']); DB::collection('users')->where('name', 'Jane Doe')->increment('age', 10, ['note' => 'adult']);
$user = DB::collection('users')->where('name', 'Jane Doe')->first(); $user = DB::collection('users')->where('name', 'Jane Doe')->first();
$this->assertEquals(20, $user['age']); $this->assertEquals(20, $user['age']);
$this->assertEquals('adult', $user['note']); $this->assertEquals('adult', $user['note']);
DB::collection('users')->where('name', 'John Doe')->decrement('age', 20, ['note' => 'minor']); DB::collection('users')->where('name', 'John Doe')->decrement('age', 20, ['note' => 'minor']);
$user = DB::collection('users')->where('name', 'John Doe')->first(); $user = DB::collection('users')->where('name', 'John Doe')->first();
$this->assertEquals(10, $user['age']); $this->assertEquals(10, $user['age']);
$this->assertEquals('minor', $user['note']); $this->assertEquals('minor', $user['note']);
DB::collection('users')->increment('age'); DB::collection('users')->increment('age');
$user = DB::collection('users')->where('name', 'John Doe')->first(); $user = DB::collection('users')->where('name', 'John Doe')->first();
$this->assertEquals(11, $user['age']); $this->assertEquals(11, $user['age']);
$user = DB::collection('users')->where('name', 'Jane Doe')->first(); $user = DB::collection('users')->where('name', 'Jane Doe')->first();
$this->assertEquals(21, $user['age']); $this->assertEquals(21, $user['age']);
$user = DB::collection('users')->where('name', 'Robert Roe')->first(); $user = DB::collection('users')->where('name', 'Robert Roe')->first();
$this->assertEquals(null, $user['age']); $this->assertEquals(null, $user['age']);
$user = DB::collection('users')->where('name', 'Mark Moe')->first(); $user = DB::collection('users')->where('name', 'Mark Moe')->first();
$this->assertEquals(1, $user['age']); $this->assertEquals(1, $user['age']);
} }
public function testProjections() public function testProjections()
{ {
DB::collection('items')->insert([ DB::collection('items')->insert([
['name' => 'fork', 'tags' => ['sharp', 'pointy']], ['name' => 'fork', 'tags' => ['sharp', 'pointy']],
['name' => 'spork', 'tags' => ['sharp', 'pointy', 'round', 'bowl']], ['name' => 'spork', 'tags' => ['sharp', 'pointy', 'round', 'bowl']],
['name' => 'spoon', 'tags' => ['round', 'bowl']], ['name' => 'spoon', 'tags' => ['round', 'bowl']],
]); ]);
$results = DB::collection('items')->project(['tags' => ['$slice' => 1]])->get(); $results = DB::collection('items')->project(['tags' => ['$slice' => 1]])->get();
foreach ($results as $result) foreach ($results as $result)
{ {
$this->assertEquals(1, count($result['tags'])); $this->assertEquals(1, count($result['tags']));
} }
} }
} }
...@@ -2,316 +2,316 @@ ...@@ -2,316 +2,316 @@
class QueryTest extends TestCase { class QueryTest extends TestCase {
protected static $started = false; protected static $started = false;
public function setUp() public function setUp()
{ {
parent::setUp(); parent::setUp();
User::create(['name' => 'John Doe', 'age' => 35, 'title' => 'admin']); User::create(['name' => 'John Doe', 'age' => 35, 'title' => 'admin']);
User::create(['name' => 'Jane Doe', 'age' => 33, 'title' => 'admin']); User::create(['name' => 'Jane Doe', 'age' => 33, 'title' => 'admin']);
User::create(['name' => 'Harry Hoe', 'age' => 13, 'title' => 'user']); User::create(['name' => 'Harry Hoe', 'age' => 13, 'title' => 'user']);
User::create(['name' => 'Robert Roe', 'age' => 37, 'title' => 'user']); User::create(['name' => 'Robert Roe', 'age' => 37, 'title' => 'user']);
User::create(['name' => 'Mark Moe', 'age' => 23, 'title' => 'user']); User::create(['name' => 'Mark Moe', 'age' => 23, 'title' => 'user']);
User::create(['name' => 'Brett Boe', 'age' => 35, 'title' => 'user']); User::create(['name' => 'Brett Boe', 'age' => 35, 'title' => 'user']);
User::create(['name' => 'Tommy Toe', 'age' => 33, 'title' => 'user']); User::create(['name' => 'Tommy Toe', 'age' => 33, 'title' => 'user']);
User::create(['name' => 'Yvonne Yoe', 'age' => 35, 'title' => 'admin']); User::create(['name' => 'Yvonne Yoe', 'age' => 35, 'title' => 'admin']);
User::create(['name' => 'Error', 'age' => null, 'title' => null]); User::create(['name' => 'Error', 'age' => null, 'title' => null]);
} }
public function tearDown() public function tearDown()
{ {
User::truncate(); User::truncate();
parent::tearDown(); parent::tearDown();
} }
public function testWhere() public function testWhere()
{ {
$users = User::where('age', 35)->get(); $users = User::where('age', 35)->get();
$this->assertEquals(3, count($users)); $this->assertEquals(3, count($users));
$users = User::where('age', '=', 35)->get(); $users = User::where('age', '=', 35)->get();
$this->assertEquals(3, count($users)); $this->assertEquals(3, count($users));
$users = User::where('age', '>=', 35)->get(); $users = User::where('age', '>=', 35)->get();
$this->assertEquals(4, count($users)); $this->assertEquals(4, count($users));
$users = User::where('age', '<=', 18)->get(); $users = User::where('age', '<=', 18)->get();
$this->assertEquals(1, count($users)); $this->assertEquals(1, count($users));
$users = User::where('age', '!=', 35)->get(); $users = User::where('age', '!=', 35)->get();
$this->assertEquals(6, count($users)); $this->assertEquals(6, count($users));
$users = User::where('age', '<>', 35)->get(); $users = User::where('age', '<>', 35)->get();
$this->assertEquals(6, count($users)); $this->assertEquals(6, count($users));
} }
public function testAndWhere() public function testAndWhere()
{ {
$users = User::where('age', 35)->where('title', 'admin')->get(); $users = User::where('age', 35)->where('title', 'admin')->get();
$this->assertEquals(2, count($users)); $this->assertEquals(2, count($users));
$users = User::where('age', '>=', 35)->where('title', 'user')->get(); $users = User::where('age', '>=', 35)->where('title', 'user')->get();
$this->assertEquals(2, count($users)); $this->assertEquals(2, count($users));
} }
public function testLike() public function testLike()
{ {
$users = User::where('name', 'like', '%doe')->get(); $users = User::where('name', 'like', '%doe')->get();
$this->assertEquals(2, count($users)); $this->assertEquals(2, count($users));
$users = User::where('name', 'like', '%y%')->get(); $users = User::where('name', 'like', '%y%')->get();
$this->assertEquals(3, count($users)); $this->assertEquals(3, count($users));
$users = User::where('name', 'LIKE', '%y%')->get(); $users = User::where('name', 'LIKE', '%y%')->get();
$this->assertEquals(3, count($users)); $this->assertEquals(3, count($users));
$users = User::where('name', 'like', 't%')->get(); $users = User::where('name', 'like', 't%')->get();
$this->assertEquals(1, count($users)); $this->assertEquals(1, count($users));
} }
public function testSelect() public function testSelect()
{ {
$user = User::where('name', 'John Doe')->select('name')->first(); $user = User::where('name', 'John Doe')->select('name')->first();
$this->assertEquals('John Doe', $user->name); $this->assertEquals('John Doe', $user->name);
$this->assertEquals(null, $user->age); $this->assertEquals(null, $user->age);
$this->assertEquals(null, $user->title); $this->assertEquals(null, $user->title);
$user = User::where('name', 'John Doe')->select('name', 'title')->first(); $user = User::where('name', 'John Doe')->select('name', 'title')->first();
$this->assertEquals('John Doe', $user->name); $this->assertEquals('John Doe', $user->name);
$this->assertEquals('admin', $user->title); $this->assertEquals('admin', $user->title);
$this->assertEquals(null, $user->age); $this->assertEquals(null, $user->age);
$user = User::where('name', 'John Doe')->select(['name', 'title'])->get()->first(); $user = User::where('name', 'John Doe')->select(['name', 'title'])->get()->first();
$this->assertEquals('John Doe', $user->name); $this->assertEquals('John Doe', $user->name);
$this->assertEquals('admin', $user->title); $this->assertEquals('admin', $user->title);
$this->assertEquals(null, $user->age); $this->assertEquals(null, $user->age);
$user = User::where('name', 'John Doe')->get(['name'])->first(); $user = User::where('name', 'John Doe')->get(['name'])->first();
$this->assertEquals('John Doe', $user->name); $this->assertEquals('John Doe', $user->name);
$this->assertEquals(null, $user->age); $this->assertEquals(null, $user->age);
} }
public function testOrWhere() public function testOrWhere()
{ {
$users = User::where('age', 13)->orWhere('title', 'admin')->get(); $users = User::where('age', 13)->orWhere('title', 'admin')->get();
$this->assertEquals(4, count($users)); $this->assertEquals(4, count($users));
$users = User::where('age', 13)->orWhere('age', 23)->get(); $users = User::where('age', 13)->orWhere('age', 23)->get();
$this->assertEquals(2, count($users)); $this->assertEquals(2, count($users));
} }
public function testBetween() public function testBetween()
{ {
$users = User::whereBetween('age', [0, 25])->get(); $users = User::whereBetween('age', [0, 25])->get();
$this->assertEquals(2, count($users)); $this->assertEquals(2, count($users));
$users = User::whereBetween('age', [13, 23])->get(); $users = User::whereBetween('age', [13, 23])->get();
$this->assertEquals(2, count($users)); $this->assertEquals(2, count($users));
// testing whereNotBetween for version 4.1 // testing whereNotBetween for version 4.1
$users = User::whereBetween('age', [0, 25], 'and', true)->get(); $users = User::whereBetween('age', [0, 25], 'and', true)->get();
$this->assertEquals(6, count($users)); $this->assertEquals(6, count($users));
} }
public function testIn() public function testIn()
{ {
$users = User::whereIn('age', [13, 23])->get(); $users = User::whereIn('age', [13, 23])->get();
$this->assertEquals(2, count($users)); $this->assertEquals(2, count($users));
$users = User::whereIn('age', [33, 35, 13])->get(); $users = User::whereIn('age', [33, 35, 13])->get();
$this->assertEquals(6, count($users)); $this->assertEquals(6, count($users));
$users = User::whereNotIn('age', [33, 35])->get(); $users = User::whereNotIn('age', [33, 35])->get();
$this->assertEquals(4, count($users)); $this->assertEquals(4, count($users));
$users = User::whereNotNull('age') $users = User::whereNotNull('age')
->whereNotIn('age', [33, 35])->get(); ->whereNotIn('age', [33, 35])->get();
$this->assertEquals(3, count($users)); $this->assertEquals(3, count($users));
} }
public function testWhereNull() public function testWhereNull()
{ {
$users = User::whereNull('age')->get(); $users = User::whereNull('age')->get();
$this->assertEquals(1, count($users)); $this->assertEquals(1, count($users));
} }
public function testWhereNotNull() public function testWhereNotNull()
{ {
$users = User::whereNotNull('age')->get(); $users = User::whereNotNull('age')->get();
$this->assertEquals(8, count($users)); $this->assertEquals(8, count($users));
} }
public function testOrder() public function testOrder()
{ {
$user = User::whereNotNull('age')->orderBy('age', 'asc')->first(); $user = User::whereNotNull('age')->orderBy('age', 'asc')->first();
$this->assertEquals(13, $user->age); $this->assertEquals(13, $user->age);
$user = User::whereNotNull('age')->orderBy('age', 'ASC')->first(); $user = User::whereNotNull('age')->orderBy('age', 'ASC')->first();
$this->assertEquals(13, $user->age); $this->assertEquals(13, $user->age);
$user = User::whereNotNull('age')->orderBy('age', 'desc')->first(); $user = User::whereNotNull('age')->orderBy('age', 'desc')->first();
$this->assertEquals(37, $user->age); $this->assertEquals(37, $user->age);
$user = User::whereNotNull('age')->orderBy('natural', 'asc')->first(); $user = User::whereNotNull('age')->orderBy('natural', 'asc')->first();
$this->assertEquals(35, $user->age); $this->assertEquals(35, $user->age);
$user = User::whereNotNull('age')->orderBy('natural', 'ASC')->first(); $user = User::whereNotNull('age')->orderBy('natural', 'ASC')->first();
$this->assertEquals(35, $user->age); $this->assertEquals(35, $user->age);
$user = User::whereNotNull('age')->orderBy('natural', 'desc')->first(); $user = User::whereNotNull('age')->orderBy('natural', 'desc')->first();
$this->assertEquals(35, $user->age); $this->assertEquals(35, $user->age);
} }
public function testGroupBy() public function testGroupBy()
{ {
$users = User::groupBy('title')->get(); $users = User::groupBy('title')->get();
$this->assertEquals(3, count($users)); $this->assertEquals(3, count($users));
$users = User::groupBy('age')->get(); $users = User::groupBy('age')->get();
$this->assertEquals(6, count($users)); $this->assertEquals(6, count($users));
$users = User::groupBy('age')->skip(1)->get(); $users = User::groupBy('age')->skip(1)->get();
$this->assertEquals(5, count($users)); $this->assertEquals(5, count($users));
$users = User::groupBy('age')->take(2)->get(); $users = User::groupBy('age')->take(2)->get();
$this->assertEquals(2, count($users)); $this->assertEquals(2, count($users));
$users = User::groupBy('age')->orderBy('age', 'desc')->get(); $users = User::groupBy('age')->orderBy('age', 'desc')->get();
$this->assertEquals(37, $users[0]->age); $this->assertEquals(37, $users[0]->age);
$this->assertEquals(35, $users[1]->age); $this->assertEquals(35, $users[1]->age);
$this->assertEquals(33, $users[2]->age); $this->assertEquals(33, $users[2]->age);
$users = User::groupBy('age')->skip(1)->take(2)->orderBy('age', 'desc')->get(); $users = User::groupBy('age')->skip(1)->take(2)->orderBy('age', 'desc')->get();
$this->assertEquals(2, count($users)); $this->assertEquals(2, count($users));
$this->assertEquals(35, $users[0]->age); $this->assertEquals(35, $users[0]->age);
$this->assertEquals(33, $users[1]->age); $this->assertEquals(33, $users[1]->age);
$this->assertNull($users[0]->name); $this->assertNull($users[0]->name);
$users = User::select('name')->groupBy('age')->skip(1)->take(2)->orderBy('age', 'desc')->get(); $users = User::select('name')->groupBy('age')->skip(1)->take(2)->orderBy('age', 'desc')->get();
$this->assertEquals(2, count($users)); $this->assertEquals(2, count($users));
$this->assertNotNull($users[0]->name); $this->assertNotNull($users[0]->name);
} }
public function testCount() public function testCount()
{ {
$count = User::where('age', '<>', 35)->count(); $count = User::where('age', '<>', 35)->count();
$this->assertEquals(6, $count); $this->assertEquals(6, $count);
// Test for issue #165 // Test for issue #165
$count = User::select('_id', 'age', 'title')->where('age', '<>', 35)->count(); $count = User::select('_id', 'age', 'title')->where('age', '<>', 35)->count();
$this->assertEquals(6, $count); $this->assertEquals(6, $count);
} }
public function testSubquery() public function testSubquery()
{ {
$users = User::where('title', 'admin')->orWhere(function($query) $users = User::where('title', 'admin')->orWhere(function ($query)
{ {
$query->where('name', 'Tommy Toe') $query->where('name', 'Tommy Toe')
->orWhere('name', 'Error'); ->orWhere('name', 'Error');
}) })
->get(); ->get();
$this->assertEquals(5, count($users)); $this->assertEquals(5, count($users));
$users = User::where('title', 'user')->where(function($query) $users = User::where('title', 'user')->where(function ($query)
{ {
$query->where('age', 35) $query->where('age', 35)
->orWhere('name', 'like', '%harry%'); ->orWhere('name', 'like', '%harry%');
}) })
->get(); ->get();
$this->assertEquals(2, count($users)); $this->assertEquals(2, count($users));
$users = User::where('age', 35)->orWhere(function($query) $users = User::where('age', 35)->orWhere(function ($query)
{ {
$query->where('title', 'admin') $query->where('title', 'admin')
->orWhere('name', 'Error'); ->orWhere('name', 'Error');
}) })
->get(); ->get();
$this->assertEquals(5, count($users)); $this->assertEquals(5, count($users));
$users = User::whereNull('deleted_at') $users = User::whereNull('deleted_at')
->where('title', 'admin') ->where('title', 'admin')
->where(function($query) ->where(function ($query)
{ {
$query->where('age', '>', 15) $query->where('age', '>', 15)
->orWhere('name', 'Harry Hoe'); ->orWhere('name', 'Harry Hoe');
}) })
->get(); ->get();
$this->assertEquals(3, $users->count()); $this->assertEquals(3, $users->count());
$users = User::whereNull('deleted_at') $users = User::whereNull('deleted_at')
->where(function($query) ->where(function ($query)
{ {
$query->where('name', 'Harry Hoe') $query->where('name', 'Harry Hoe')
->orWhere(function($query) ->orWhere(function ($query)
{ {
$query->where('age', '>', 15) $query->where('age', '>', 15)
->where('title', '<>', 'admin'); ->where('title', '<>', 'admin');
}); });
}) })
->get(); ->get();
$this->assertEquals(5, $users->count()); $this->assertEquals(5, $users->count());
} }
public function testWhereRaw() public function testWhereRaw()
{ {
$where = ['age' => ['$gt' => 30, '$lt' => 40]]; $where = ['age' => ['$gt' => 30, '$lt' => 40]];
$users = User::whereRaw($where)->get(); $users = User::whereRaw($where)->get();
$this->assertEquals(6, count($users)); $this->assertEquals(6, count($users));
$where1 = ['age' => ['$gt' => 30, '$lte' => 35]]; $where1 = ['age' => ['$gt' => 30, '$lte' => 35]];
$where2 = ['age' => ['$gt' => 35, '$lt' => 40]]; $where2 = ['age' => ['$gt' => 35, '$lt' => 40]];
$users = User::whereRaw($where1)->orWhereRaw($where2)->get(); $users = User::whereRaw($where1)->orWhereRaw($where2)->get();
$this->assertEquals(6, count($users)); $this->assertEquals(6, count($users));
} }
public function testMultipleOr() public function testMultipleOr()
{ {
$users = User::where(function($query) $users = User::where(function ($query)
{ {
$query->where('age', 35)->orWhere('age', 33); $query->where('age', 35)->orWhere('age', 33);
}) })
->where(function($query) ->where(function ($query)
{ {
$query->where('name', 'John Doe')->orWhere('name', 'Jane Doe'); $query->where('name', 'John Doe')->orWhere('name', 'Jane Doe');
})->get(); })->get();
$this->assertEquals(2, count($users)); $this->assertEquals(2, count($users));
$users = User::where(function($query) $users = User::where(function ($query)
{ {
$query->orWhere('age', 35)->orWhere('age', 33); $query->orWhere('age', 35)->orWhere('age', 33);
}) })
->where(function($query) ->where(function ($query)
{ {
$query->orWhere('name', 'John Doe')->orWhere('name', 'Jane Doe'); $query->orWhere('name', 'John Doe')->orWhere('name', 'Jane Doe');
})->get(); })->get();
$this->assertEquals(2, count($users)); $this->assertEquals(2, count($users));
} }
public function testPaginate() public function testPaginate()
{ {
$results = User::paginate(2); $results = User::paginate(2);
$this->assertEquals(2, $results->count()); $this->assertEquals(2, $results->count());
$this->assertNotNull($results->first()->title); $this->assertNotNull($results->first()->title);
$this->assertEquals(9, $results->total()); $this->assertEquals(9, $results->total());
$results = User::paginate(2, ['name', 'age']); $results = User::paginate(2, ['name', 'age']);
$this->assertEquals(2, $results->count()); $this->assertEquals(2, $results->count());
$this->assertNull($results->first()->title); $this->assertNull($results->first()->title);
$this->assertEquals(9, $results->total()); $this->assertEquals(9, $results->total());
$this->assertEquals(1, $results->currentPage()); $this->assertEquals(1, $results->currentPage());
} }
} }
...@@ -228,12 +228,12 @@ class RelationsTest extends TestCase { ...@@ -228,12 +228,12 @@ class RelationsTest extends TestCase {
$clients = [ $clients = [
Client::create(['name' => 'Pork Pies Ltd.'])->_id, Client::create(['name' => 'Pork Pies Ltd.'])->_id,
Client::create(['name' => 'Buffet Bar Inc.'])->_id Client::create(['name' => 'Buffet Bar Inc.'])->_id,
]; ];
$moreClients = [ $moreClients = [
Client::create(['name' => 'synced Boloni Ltd.'])->_id, Client::create(['name' => 'synced Boloni Ltd.'])->_id,
Client::create(['name' => 'synced Meatballs Inc.'])->_id Client::create(['name' => 'synced Meatballs Inc.'])->_id,
]; ];
// Sync multiple records // Sync multiple records
...@@ -410,14 +410,14 @@ class RelationsTest extends TestCase { ...@@ -410,14 +410,14 @@ class RelationsTest extends TestCase {
$authors = User::has('books', '!=', 0)->get(); $authors = User::has('books', '!=', 0)->get();
$this->assertCount(2, $authors); $this->assertCount(2, $authors);
$authors = User::whereHas('books', function($query) $authors = User::whereHas('books', function ($query)
{ {
$query->where('rating', 5); $query->where('rating', 5);
})->get(); })->get();
$this->assertCount(1, $authors); $this->assertCount(1, $authors);
$authors = User::whereHas('books', function($query) $authors = User::whereHas('books', function ($query)
{ {
$query->where('rating', '<', 5); $query->where('rating', '<', 5);
...@@ -451,15 +451,15 @@ class RelationsTest extends TestCase { ...@@ -451,15 +451,15 @@ class RelationsTest extends TestCase {
$client = Client::create([ $client = Client::create([
'data' => [ 'data' => [
'client_id' => 35298, 'client_id' => 35298,
'name' => 'John Doe' 'name' => 'John Doe',
] ],
]); ]);
$address = $client->addresses()->create([ $address = $client->addresses()->create([
'data' => [ 'data' => [
'address_id' => 1432, 'address_id' => 1432,
'city' => 'Paris' 'city' => 'Paris',
] ],
]); ]);
$client = Client::where('data.client_id', 35298)->first(); $client = Client::where('data.client_id', 35298)->first();
......
...@@ -2,187 +2,187 @@ ...@@ -2,187 +2,187 @@
class SchemaTest extends TestCase { class SchemaTest extends TestCase {
public function tearDown() public function tearDown()
{ {
Schema::drop('newcollection'); Schema::drop('newcollection');
} }
public function testCreate() public function testCreate()
{ {
Schema::create('newcollection'); Schema::create('newcollection');
$this->assertTrue(Schema::hasCollection('newcollection')); $this->assertTrue(Schema::hasCollection('newcollection'));
$this->assertTrue(Schema::hasTable('newcollection')); $this->assertTrue(Schema::hasTable('newcollection'));
} }
public function testCreateWithCallback() public function testCreateWithCallback()
{ {
$instance = $this; $instance = $this;
Schema::create('newcollection', function($collection) use ($instance) Schema::create('newcollection', function ($collection) use ($instance)
{ {
$instance->assertInstanceOf('Jenssegers\Mongodb\Schema\Blueprint', $collection); $instance->assertInstanceOf('Jenssegers\Mongodb\Schema\Blueprint', $collection);
}); });
$this->assertTrue(Schema::hasCollection('newcollection')); $this->assertTrue(Schema::hasCollection('newcollection'));
} }
public function testDrop() public function testDrop()
{ {
Schema::create('newcollection'); Schema::create('newcollection');
Schema::drop('newcollection'); Schema::drop('newcollection');
$this->assertFalse(Schema::hasCollection('newcollection')); $this->assertFalse(Schema::hasCollection('newcollection'));
} }
public function testBluePrint() public function testBluePrint()
{ {
$instance = $this; $instance = $this;
Schema::collection('newcollection', function($collection) use ($instance) Schema::collection('newcollection', function ($collection) use ($instance)
{ {
$instance->assertInstanceOf('Jenssegers\Mongodb\Schema\Blueprint', $collection); $instance->assertInstanceOf('Jenssegers\Mongodb\Schema\Blueprint', $collection);
}); });
Schema::table('newcollection', function($collection) use ($instance) Schema::table('newcollection', function ($collection) use ($instance)
{ {
$instance->assertInstanceOf('Jenssegers\Mongodb\Schema\Blueprint', $collection); $instance->assertInstanceOf('Jenssegers\Mongodb\Schema\Blueprint', $collection);
}); });
} }
public function testIndex() public function testIndex()
{ {
Schema::collection('newcollection', function($collection) Schema::collection('newcollection', function ($collection)
{ {
$collection->index('mykey'); $collection->index('mykey');
}); });
$index = $this->getIndex('newcollection', 'mykey'); $index = $this->getIndex('newcollection', 'mykey');
$this->assertEquals(1, $index['key']['mykey']); $this->assertEquals(1, $index['key']['mykey']);
Schema::collection('newcollection', function($collection) Schema::collection('newcollection', function ($collection)
{ {
$collection->index(['mykey']); $collection->index(['mykey']);
}); });
$index = $this->getIndex('newcollection', 'mykey'); $index = $this->getIndex('newcollection', 'mykey');
$this->assertEquals(1, $index['key']['mykey']); $this->assertEquals(1, $index['key']['mykey']);
} }
public function testUnique() public function testUnique()
{ {
Schema::collection('newcollection', function($collection) Schema::collection('newcollection', function ($collection)
{ {
$collection->unique('uniquekey'); $collection->unique('uniquekey');
}); });
$index = $this->getIndex('newcollection', 'uniquekey'); $index = $this->getIndex('newcollection', 'uniquekey');
$this->assertEquals(1, $index['unique']); $this->assertEquals(1, $index['unique']);
} }
public function testDropIndex() public function testDropIndex()
{ {
Schema::collection('newcollection', function($collection) Schema::collection('newcollection', function ($collection)
{ {
$collection->unique('uniquekey'); $collection->unique('uniquekey');
$collection->dropIndex('uniquekey'); $collection->dropIndex('uniquekey');
}); });
$index = $this->getIndex('newcollection', 'uniquekey'); $index = $this->getIndex('newcollection', 'uniquekey');
$this->assertEquals(null, $index); $this->assertEquals(null, $index);
Schema::collection('newcollection', function($collection) Schema::collection('newcollection', function ($collection)
{ {
$collection->unique('uniquekey'); $collection->unique('uniquekey');
$collection->dropIndex(['uniquekey']); $collection->dropIndex(['uniquekey']);
}); });
$index = $this->getIndex('newcollection', 'uniquekey'); $index = $this->getIndex('newcollection', 'uniquekey');
$this->assertEquals(null, $index); $this->assertEquals(null, $index);
} }
public function testBackground() public function testBackground()
{ {
Schema::collection('newcollection', function($collection) Schema::collection('newcollection', function ($collection)
{ {
$collection->background('backgroundkey'); $collection->background('backgroundkey');
}); });
$index = $this->getIndex('newcollection', 'backgroundkey'); $index = $this->getIndex('newcollection', 'backgroundkey');
$this->assertEquals(1, $index['background']); $this->assertEquals(1, $index['background']);
} }
public function testSparse() public function testSparse()
{ {
Schema::collection('newcollection', function($collection) Schema::collection('newcollection', function ($collection)
{ {
$collection->sparse('sparsekey'); $collection->sparse('sparsekey');
}); });
$index = $this->getIndex('newcollection', 'sparsekey'); $index = $this->getIndex('newcollection', 'sparsekey');
$this->assertEquals(1, $index['sparse']); $this->assertEquals(1, $index['sparse']);
} }
public function testExpire() public function testExpire()
{ {
Schema::collection('newcollection', function($collection) Schema::collection('newcollection', function ($collection)
{ {
$collection->expire('expirekey', 60); $collection->expire('expirekey', 60);
}); });
$index = $this->getIndex('newcollection', 'expirekey'); $index = $this->getIndex('newcollection', 'expirekey');
$this->assertEquals(60, $index['expireAfterSeconds']); $this->assertEquals(60, $index['expireAfterSeconds']);
} }
public function testSoftDeletes() public function testSoftDeletes()
{ {
Schema::collection('newcollection', function($collection) Schema::collection('newcollection', function ($collection)
{ {
$collection->softDeletes(); $collection->softDeletes();
}); });
Schema::collection('newcollection', function($collection) Schema::collection('newcollection', function ($collection)
{ {
$collection->string('email')->nullable()->index(); $collection->string('email')->nullable()->index();
}); });
$index = $this->getIndex('newcollection', 'email'); $index = $this->getIndex('newcollection', 'email');
$this->assertEquals(1, $index['key']['email']); $this->assertEquals(1, $index['key']['email']);
} }
public function testFluent() public function testFluent()
{ {
Schema::collection('newcollection', function($collection) Schema::collection('newcollection', function ($collection)
{ {
$collection->string('email')->index(); $collection->string('email')->index();
$collection->string('token')->index(); $collection->string('token')->index();
$collection->timestamp('created_at'); $collection->timestamp('created_at');
}); });
$index = $this->getIndex('newcollection', 'email'); $index = $this->getIndex('newcollection', 'email');
$this->assertEquals(1, $index['key']['email']); $this->assertEquals(1, $index['key']['email']);
$index = $this->getIndex('newcollection', 'token'); $index = $this->getIndex('newcollection', 'token');
$this->assertEquals(1, $index['key']['token']); $this->assertEquals(1, $index['key']['token']);
} }
public function testDummies() public function testDummies()
{ {
Schema::collection('newcollection', function($collection) Schema::collection('newcollection', function ($collection)
{ {
$collection->boolean('activated')->default(0); $collection->boolean('activated')->default(0);
$collection->integer('user_id')->unsigned(); $collection->integer('user_id')->unsigned();
}); });
} }
protected function getIndex($collection, $name) protected function getIndex($collection, $name)
{ {
$collection = DB::getCollection($collection); $collection = DB::getCollection($collection);
foreach ($collection->getIndexInfo() as $index) foreach ($collection->getIndexInfo() as $index)
{ {
if (isset($index['key'][$name])) return $index; if (isset($index['key'][$name])) return $index;
} }
return false; return false;
} }
} }
...@@ -2,26 +2,26 @@ ...@@ -2,26 +2,26 @@
class SeederTest extends TestCase { class SeederTest extends TestCase {
public function tearDown() public function tearDown()
{ {
User::truncate(); User::truncate();
} }
public function testSeed() public function testSeed()
{ {
$seeder = new UserTableSeeder; $seeder = new UserTableSeeder;
$seeder->run(); $seeder->run();
$user = User::where('name', 'John Doe')->first(); $user = User::where('name', 'John Doe')->first();
$this->assertTrue($user->seed); $this->assertTrue($user->seed);
} }
public function testArtisan() public function testArtisan()
{ {
Artisan::call('db:seed'); Artisan::call('db:seed');
$user = User::where('name', 'John Doe')->first(); $user = User::where('name', 'John Doe')->first();
$this->assertTrue($user->seed); $this->assertTrue($user->seed);
} }
} }
...@@ -2,25 +2,25 @@ ...@@ -2,25 +2,25 @@
return [ return [
'connections' => [ 'connections' => [
'mongodb' => [ 'mongodb' => [
'name' => 'mongodb', 'name' => 'mongodb',
'driver' => 'mongodb', 'driver' => 'mongodb',
'host' => '127.0.0.1', 'host' => '127.0.0.1',
'database' => 'unittest', 'database' => 'unittest',
], ],
'mysql' => [ 'mysql' => [
'driver' => 'mysql', 'driver' => 'mysql',
'host' => '127.0.0.1', 'host' => '127.0.0.1',
'database' => 'unittest', 'database' => 'unittest',
'username' => 'travis', 'username' => 'travis',
'password' => '', 'password' => '',
'charset' => 'utf8', 'charset' => 'utf8',
'collation' => 'utf8_unicode_ci', 'collation' => 'utf8_unicode_ci',
'prefix' => '', 'prefix' => '',
], ],
] ],
]; ];
...@@ -4,9 +4,9 @@ use Jenssegers\Mongodb\Model as Eloquent; ...@@ -4,9 +4,9 @@ use Jenssegers\Mongodb\Model as Eloquent;
class Book extends Eloquent { class Book extends Eloquent {
protected $collection = 'books'; protected $collection = 'books';
protected static $unguarded = true; protected static $unguarded = true;
protected $primaryKey = 'title'; protected $primaryKey = 'title';
public function author() public function author()
{ {
......
...@@ -4,15 +4,15 @@ use Jenssegers\Mongodb\Model as Eloquent; ...@@ -4,15 +4,15 @@ use Jenssegers\Mongodb\Model as Eloquent;
class Client extends Eloquent { class Client extends Eloquent {
protected $collection = 'clients'; protected $collection = 'clients';
protected static $unguarded = true; protected static $unguarded = true;
public function users() public function users()
{ {
return $this->belongsToMany('User'); return $this->belongsToMany('User');
} }
public function photo() public function photo()
{ {
return $this->morphOne('Photo', 'imageable'); return $this->morphOne('Photo', 'imageable');
} }
......
...@@ -4,11 +4,11 @@ use Jenssegers\Mongodb\Model as Eloquent; ...@@ -4,11 +4,11 @@ use Jenssegers\Mongodb\Model as Eloquent;
class Group extends Eloquent { class Group extends Eloquent {
protected $collection = 'groups'; protected $collection = 'groups';
protected static $unguarded = true; protected static $unguarded = true;
public function users() public function users()
{ {
return $this->belongsToMany('User', null, 'groups', 'users'); return $this->belongsToMany('User', null, 'groups', 'users');
} }
} }
...@@ -4,17 +4,17 @@ use Jenssegers\Mongodb\Model as Eloquent; ...@@ -4,17 +4,17 @@ use Jenssegers\Mongodb\Model as Eloquent;
class Item extends Eloquent { class Item extends Eloquent {
protected $collection = 'items'; protected $collection = 'items';
protected static $unguarded = true; protected static $unguarded = true;
public function user() public function user()
{ {
return $this->belongsTo('User'); return $this->belongsTo('User');
} }
public function scopeSharp($query) public function scopeSharp($query)
{ {
return $query->where('type', 'sharp'); return $query->where('type', 'sharp');
} }
} }
...@@ -6,9 +6,9 @@ use Jenssegers\Eloquent\Model as Eloquent; ...@@ -6,9 +6,9 @@ use Jenssegers\Eloquent\Model as Eloquent;
class MysqlBook extends Eloquent { class MysqlBook extends Eloquent {
protected $connection = 'mysql'; protected $connection = 'mysql';
protected $table = 'books'; protected $table = 'books';
protected static $unguarded = true; protected static $unguarded = true;
protected $primaryKey = 'title'; protected $primaryKey = 'title';
public function author() public function author()
{ {
...@@ -16,7 +16,7 @@ class MysqlBook extends Eloquent { ...@@ -16,7 +16,7 @@ class MysqlBook extends Eloquent {
} }
/** /**
* Check if we need to run the schema * Check if we need to run the schema.
* @return [type] [description] * @return [type] [description]
*/ */
public static function executeSchema() public static function executeSchema()
...@@ -25,7 +25,7 @@ class MysqlBook extends Eloquent { ...@@ -25,7 +25,7 @@ class MysqlBook extends Eloquent {
if (!$schema->hasTable('books')) if (!$schema->hasTable('books'))
{ {
Schema::connection('mysql')->create('books', function($table) Schema::connection('mysql')->create('books', function ($table)
{ {
$table->string('title'); $table->string('title');
$table->string('author_id'); $table->string('author_id');
......
...@@ -6,21 +6,21 @@ use Jenssegers\Eloquent\Model as Eloquent; ...@@ -6,21 +6,21 @@ use Jenssegers\Eloquent\Model as Eloquent;
class MysqlRole extends Eloquent { class MysqlRole extends Eloquent {
protected $connection = 'mysql'; protected $connection = 'mysql';
protected $table = 'roles'; protected $table = 'roles';
protected static $unguarded = true; protected static $unguarded = true;
public function user() public function user()
{ {
return $this->belongsTo('User'); return $this->belongsTo('User');
} }
public function mysqlUser() public function mysqlUser()
{ {
return $this->belongsTo('MysqlUser'); return $this->belongsTo('MysqlUser');
} }
/** /**
* Check if we need to run the schema * Check if we need to run the schema.
* @return [type] [description] * @return [type] [description]
*/ */
public static function executeSchema() public static function executeSchema()
...@@ -29,7 +29,7 @@ class MysqlRole extends Eloquent { ...@@ -29,7 +29,7 @@ class MysqlRole extends Eloquent {
if (!$schema->hasTable('roles')) if (!$schema->hasTable('roles'))
{ {
Schema::connection('mysql')->create('roles', function($table) Schema::connection('mysql')->create('roles', function ($table)
{ {
$table->string('type'); $table->string('type');
$table->string('user_id'); $table->string('user_id');
......
...@@ -5,7 +5,7 @@ use Jenssegers\Eloquent\Model as Eloquent; ...@@ -5,7 +5,7 @@ use Jenssegers\Eloquent\Model as Eloquent;
class MysqlUser extends Eloquent { class MysqlUser extends Eloquent {
protected $connection = 'mysql'; protected $connection = 'mysql';
protected $table = 'users'; protected $table = 'users';
protected static $unguarded = true; protected static $unguarded = true;
...@@ -20,7 +20,7 @@ class MysqlUser extends Eloquent { ...@@ -20,7 +20,7 @@ class MysqlUser extends Eloquent {
} }
/** /**
* Check if we need to run the schema * Check if we need to run the schema.
* @return [type] [description] * @return [type] [description]
*/ */
public static function executeSchema() public static function executeSchema()
...@@ -29,7 +29,7 @@ class MysqlUser extends Eloquent { ...@@ -29,7 +29,7 @@ class MysqlUser extends Eloquent {
if (!$schema->hasTable('users')) if (!$schema->hasTable('users'))
{ {
Schema::connection('mysql')->create('users', function($table) Schema::connection('mysql')->create('users', function ($table)
{ {
$table->increments('id'); $table->increments('id');
$table->string('name'); $table->string('name');
......
...@@ -4,8 +4,8 @@ use Jenssegers\Mongodb\Model as Eloquent; ...@@ -4,8 +4,8 @@ use Jenssegers\Mongodb\Model as Eloquent;
class Photo extends Eloquent { class Photo extends Eloquent {
protected $collection = 'photos'; protected $collection = 'photos';
protected static $unguarded = true; protected static $unguarded = true;
public function imageable() public function imageable()
{ {
......
...@@ -4,17 +4,17 @@ use Jenssegers\Mongodb\Model as Eloquent; ...@@ -4,17 +4,17 @@ use Jenssegers\Mongodb\Model as Eloquent;
class Role extends Eloquent { class Role extends Eloquent {
protected $collection = 'roles'; protected $collection = 'roles';
protected static $unguarded = true; protected static $unguarded = true;
public function user() public function user()
{ {
return $this->belongsTo('User'); return $this->belongsTo('User');
} }
public function mysqlUser() public function mysqlUser()
{ {
return $this->belongsTo('MysqlUser'); return $this->belongsTo('MysqlUser');
} }
} }
<?php <?php
use Jenssegers\Mongodb\Model as Eloquent; use Jenssegers\Mongodb\Model as Eloquent;
use Illuminate\Auth\Authenticatable; use Illuminate\Auth\Authenticatable;
use Illuminate\Auth\Passwords\CanResetPassword; use Illuminate\Auth\Passwords\CanResetPassword;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract; use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
...@@ -11,10 +10,10 @@ class User extends Eloquent implements AuthenticatableContract, CanResetPassword ...@@ -11,10 +10,10 @@ class User extends Eloquent implements AuthenticatableContract, CanResetPassword
use Authenticatable, CanResetPassword; use Authenticatable, CanResetPassword;
protected $dates = ['birthday', 'entry.date']; protected $dates = ['birthday', 'entry.date'];
protected static $unguarded = true; protected static $unguarded = true;
public function books() public function books()
{ {
return $this->hasMany('Book', 'author_id'); return $this->hasMany('Book', 'author_id');
} }
...@@ -39,10 +38,10 @@ class User extends Eloquent implements AuthenticatableContract, CanResetPassword ...@@ -39,10 +38,10 @@ class User extends Eloquent implements AuthenticatableContract, CanResetPassword
return $this->hasOne('MysqlRole'); return $this->hasOne('MysqlRole');
} }
public function clients() public function clients()
{ {
return $this->belongsToMany('Client'); return $this->belongsToMany('Client');
} }
public function groups() public function groups()
{ {
......
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