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