From afc57a05d894af7807765e1f6c8977fb81f26793 Mon Sep 17 00:00:00 2001 From: hooman naghiee Date: Sat, 7 May 2016 01:11:21 +0430 Subject: [PATCH 01/88] add save cast to cast data before saving data into mongoDB --- src/Jenssegers/Mongodb/Eloquent/Model.php | 127 +++++++++++++++++++++- 1 file changed, 121 insertions(+), 6 deletions(-) diff --git a/src/Jenssegers/Mongodb/Eloquent/Model.php b/src/Jenssegers/Mongodb/Eloquent/Model.php index ac31833f1..899379041 100644 --- a/src/Jenssegers/Mongodb/Eloquent/Model.php +++ b/src/Jenssegers/Mongodb/Eloquent/Model.php @@ -38,6 +38,14 @@ abstract class Model extends BaseModel */ protected $parentRelation; + /** + * The attributes that should be cast to native types. + * + * @var array + */ + protected $saveCasts = []; + + /** * Custom accessor for the model's id. * @@ -279,15 +287,15 @@ protected function getAttributeFromArray($key) */ public function setAttribute($key, $value) { - // Convert _id to ObjectID. - if ($key == '_id' and is_string($value)) { - $builder = $this->newBaseQueryBuilder(); - - $value = $builder->convertKey($value); + // cast data for saving. + // set _id to converted into ObjectID if its possible. + $this->saveCasts['_id'] = 'ObjectID'; + if($this->hasSaveCast($key)){ + $value = $this->saveCastAttribute($key, $value); } // Support keys in dot notation. - elseif (str_contains($key, '.')) { + if (str_contains($key, '.')) { if (in_array($key, $this->getDates()) && $value) { $value = $this->fromDateTime($value); } @@ -541,4 +549,111 @@ public function __call($method, $parameters) return parent::__call($method, $parameters); } + + /** + * Get the saving casts array. + * + * @return array + */ + public function getSaveCasts() + { + return $this->saveCasts; + } + + /** + * Get the type of save cast for a model attribute. + * + * @param string $key + * @return string + */ + protected function getSaveCastType($key) + { + return trim(strtolower($this->getSaveCasts()[$key])); + } + + /** + * Determine whether an attribute should be cast to a native type. + * + * @param string $key + * @param array|string|null $types + * @return bool + */ + public function hasSaveCast($key, $types = null) + { + if (array_key_exists($key, $this->getSaveCasts())) { + return $types ? in_array($this->getSaveCastType($key), (array) $types, true) : true; + } + + return false; + } + + + + /** + * Cast an attribute to a mongo type. + * + * @param string $key + * @param mixed $value + * @return mixed + */ + protected function saveCastAttribute($key, $value) + { + if (is_null($value)) { + return null; + } + + switch ($this->getSaveCastType($key)) { + case 'int': + case 'integer': + return (int)$value; + case 'real': + case 'float': + case 'double': + return (float)$value; + case 'string': + return (string)$value; + case 'bool': + case 'boolean': + return (bool)$value; + case 'date': + case 'utcdatetime': + case 'mongodate': + return $this->asMongoDate($value); + case 'objectid': + return $this->asMongoID($value); + case 'timestamp': + return $this->asTimeStamp($value); + default: + return $value; + } + } + + /** + * convert value into ObjectID if its possible + * + * @param $value + * @return UTCDatetime + */ + protected function asMongoID($value) + { + if (is_string($value) and strlen($value) === 24 and ctype_xdigit($value)) { + return new ObjectID($value); + } + + return $value; + } + + /** + * convert value into UTCDatetime + * @param $value + * @return UTCDatetime + */ + protected function asMongoDate($value) + { + if ($value instanceof UTCDatetime) { + return $value; + } + + return new UTCDatetime($this->asTimeStamp($value) * 1000); + } } From 81d2279e5ae83039482aa90a1574b561f84294b1 Mon Sep 17 00:00:00 2001 From: hooman naghiee Date: Tue, 10 May 2016 12:39:29 +0430 Subject: [PATCH 02/88] fix addHasWhere to always have string in array_count_values --- src/Jenssegers/Mongodb/Eloquent/Builder.php | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/src/Jenssegers/Mongodb/Eloquent/Builder.php b/src/Jenssegers/Mongodb/Eloquent/Builder.php index 3e21468a6..c6ed637b6 100644 --- a/src/Jenssegers/Mongodb/Eloquent/Builder.php +++ b/src/Jenssegers/Mongodb/Eloquent/Builder.php @@ -167,7 +167,11 @@ protected function addHasWhere(EloquentBuilder $hasQuery, Relation $relation, $o $query = $hasQuery->getQuery(); // Get the number of related objects for each possible parent. - $relationCount = array_count_values($query->lists($relation->getHasCompareKey())); + $compareKeys = $query->pluck($relation->getHasCompareKey()); + $compareKeys = array_map(function ($id) { + return (string)$id; + }, $compareKeys); + $relationCount = array_count_values($compareKeys); // Remove unwanted related objects based on the operator and count. $relationCount = array_filter($relationCount, function ($counted) use ($count, $operator) { From dc20406326a0ca9a96fbe1d05bc1e32c9cf86c2b Mon Sep 17 00:00:00 2001 From: hooman naghiee Date: Tue, 10 May 2016 12:40:53 +0430 Subject: [PATCH 03/88] fix addHasWhere to get proper id's from castAttribute --- src/Jenssegers/Mongodb/Eloquent/Builder.php | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/src/Jenssegers/Mongodb/Eloquent/Builder.php b/src/Jenssegers/Mongodb/Eloquent/Builder.php index c6ed637b6..2b888b8c9 100644 --- a/src/Jenssegers/Mongodb/Eloquent/Builder.php +++ b/src/Jenssegers/Mongodb/Eloquent/Builder.php @@ -202,7 +202,15 @@ protected function addHasWhere(EloquentBuilder $hasQuery, Relation $relation, $o } // All related ids. - $relatedIds = array_keys($relationCount); + $relatedIds = array_map(function ($id) use ($relation) { + $relationModel = $relation->getRelated(); + $relationModel->setRelationCast($relation->getHasCompareKey()); + if($relationModel->hasCast($relation->getHasCompareKey(), null,'set')){ + $id = $relationModel->castAttribute($relation->getHasCompareKey(), $id,'set'); + } + return $id; + }, array_keys($relationCount)); + // Add whereIn to the query. return $this->whereIn($this->model->getKeyName(), $relatedIds, $boolean, $not); From 8ce502a026baa333ad234f20517d448a65b11faa Mon Sep 17 00:00:00 2001 From: hooman naghiee Date: Tue, 10 May 2016 12:46:13 +0430 Subject: [PATCH 04/88] overwrite eloquent cast methods to make that work for set data too setRelationCast add relation that ended with _id into objectId if config allow it --- src/Jenssegers/Mongodb/Eloquent/Model.php | 72 ++++++++++++++--------- 1 file changed, 43 insertions(+), 29 deletions(-) diff --git a/src/Jenssegers/Mongodb/Eloquent/Model.php b/src/Jenssegers/Mongodb/Eloquent/Model.php index 899379041..8142c78cf 100644 --- a/src/Jenssegers/Mongodb/Eloquent/Model.php +++ b/src/Jenssegers/Mongodb/Eloquent/Model.php @@ -289,10 +289,8 @@ public function setAttribute($key, $value) { // cast data for saving. // set _id to converted into ObjectID if its possible. - $this->saveCasts['_id'] = 'ObjectID'; - if($this->hasSaveCast($key)){ - $value = $this->saveCastAttribute($key, $value); - } + $this->setRelationCast($key); + $value = $this->castAttribute($key, $value,'set'); // Support keys in dot notation. if (str_contains($key, '.')) { @@ -337,16 +335,6 @@ public function attributesToArray() return $attributes; } - /** - * Get the casts array. - * - * @return array - */ - public function getCasts() - { - return $this->casts; - } - /** * Determine if the new and old values for a given key are numerically equivalent. * @@ -551,58 +539,68 @@ public function __call($method, $parameters) } /** - * Get the saving casts array. + * Get the casts array. * + * @param string $castType * @return array */ - public function getSaveCasts() + public function getCasts($castType = 'get') { - return $this->saveCasts; + if ($castType == 'set') { + return $this->saveCasts; + } + return $this->casts; } /** * Get the type of save cast for a model attribute. * * @param string $key + * @param string $castType * @return string */ - protected function getSaveCastType($key) + protected function getCastType($key, $castType = 'get') { - return trim(strtolower($this->getSaveCasts()[$key])); + return trim(strtolower($this->getCasts($castType)[$key])); } /** * Determine whether an attribute should be cast to a native type. * - * @param string $key - * @param array|string|null $types + * @param string $key + * @param array|string|null $types + * @param string $castType * @return bool */ - public function hasSaveCast($key, $types = null) + public function hasCast($key, $types = null, $castType = 'get') { - if (array_key_exists($key, $this->getSaveCasts())) { - return $types ? in_array($this->getSaveCastType($key), (array) $types, true) : true; + if (array_key_exists($key, $this->getCasts($castType))) { + return $types ? in_array($this->getCastType($key, $castType), (array)$types, true) : true; } return false; } - /** * Cast an attribute to a mongo type. * * @param string $key * @param mixed $value + * @param string $castType * @return mixed */ - protected function saveCastAttribute($key, $value) + public function castAttribute($key, $value, $castType = 'get') { if (is_null($value)) { return null; } - switch ($this->getSaveCastType($key)) { + if (!$this->hasCast($key, null, $castType)) { + return $value; + } + + switch ($this->getCastType($key, $castType)) { case 'int': case 'integer': return (int)$value; @@ -619,6 +617,7 @@ protected function saveCastAttribute($key, $value) case 'utcdatetime': case 'mongodate': return $this->asMongoDate($value); + case 'mongoid': case 'objectid': return $this->asMongoID($value); case 'timestamp': @@ -639,10 +638,9 @@ protected function asMongoID($value) if (is_string($value) and strlen($value) === 24 and ctype_xdigit($value)) { return new ObjectID($value); } - return $value; } - + /** * convert value into UTCDatetime * @param $value @@ -656,4 +654,20 @@ protected function asMongoDate($value) return new UTCDatetime($this->asTimeStamp($value) * 1000); } + + /** + * add relation that ended with _id into objectId + * if config allow it + * + * @param $key + */ + public function setRelationCast($key) + { + $useMongoId = config('database.connections.mongodb.use_mongo_id',false); + if($useMongoId){ + if (ends_with($key, '_id')) { + $this->saveCasts[$key] = 'ObjectID'; + } + } + } } From ecf8feb88e98c852c555cb4f12f8304470cd1105 Mon Sep 17 00:00:00 2001 From: hooman naghiee Date: Tue, 10 May 2016 12:46:54 +0430 Subject: [PATCH 05/88] fix BelongsTo's match method --- .../Mongodb/Relations/BelongsTo.php | 30 +++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/src/Jenssegers/Mongodb/Relations/BelongsTo.php b/src/Jenssegers/Mongodb/Relations/BelongsTo.php index b73c6b05e..d424f7063 100644 --- a/src/Jenssegers/Mongodb/Relations/BelongsTo.php +++ b/src/Jenssegers/Mongodb/Relations/BelongsTo.php @@ -29,4 +29,34 @@ public function addEagerConstraints(array $models) $this->query->whereIn($key, $this->getEagerModelKeys($models)); } + + /** + * Match the eagerly loaded results to their parents. + * + * @param array $models + * @param \Illuminate\Database\Eloquent\Collection $results + * @param string $relation + * @return array + */ + public function match(array $models, \Illuminate\Database\Eloquent\Collection $results, $relation) + { + $foreign = $this->foreignKey; + $other = $this->otherKey; + // First we will get to build a dictionary of the child models by their primary + // key of the relationship, then we can easily match the children back onto + // the parents using that dictionary and the primary key of the children. + $dictionary = []; + foreach ($results as $result) { + $dictionary[$result->getAttribute($other)] = $result; + } + // Once we have the dictionary constructed, we can loop through all the parents + // and match back onto their children using these keys of the dictionary and + // the primary key of the children to map them onto the correct instances. + foreach ($models as $model) { + if (isset($dictionary[(string)$model->$foreign])) { + $model->setRelation($relation, $dictionary[(string)$model->$foreign]); + } + } + return $models; + } } From 0aa0297b3b6749295a076a18b1357320e9ebd68b Mon Sep 17 00:00:00 2001 From: hooman naghiee Date: Tue, 10 May 2016 12:47:20 +0430 Subject: [PATCH 06/88] add HasOneOrManyTrait trait --- .../Mongodb/Relations/HasOneOrManyTrait.php | 65 +++++++++++++++++++ 1 file changed, 65 insertions(+) create mode 100644 src/Jenssegers/Mongodb/Relations/HasOneOrManyTrait.php diff --git a/src/Jenssegers/Mongodb/Relations/HasOneOrManyTrait.php b/src/Jenssegers/Mongodb/Relations/HasOneOrManyTrait.php new file mode 100644 index 000000000..6248efebc --- /dev/null +++ b/src/Jenssegers/Mongodb/Relations/HasOneOrManyTrait.php @@ -0,0 +1,65 @@ +setRelationCast($key); + $id = $key ? $model->getAttribute($key) : $model->getKey(); + return $model->castAttribute($key, $id,'set'); + }, $models))); + } + + /** + * Build model dictionary keyed by the relation's foreign key. + * + * @param \Illuminate\Database\Eloquent\Collection $results + * @return array + */ + protected function buildDictionary(Collection $results) + { + $dictionary = []; + $foreign = $this->getPlainForeignKey(); + // First we will create a dictionary of models keyed by the foreign key of the + // relationship as this will allow us to quickly access all of the related + // models without having to do nested looping which will be quite slow. + foreach ($results as $result) { + $dictionary[(string)$result->{$foreign}][] = $result; + } + return $dictionary; + } + + /** + * Get the key value of the parent's local key. + * + * @return mixed + */ + public function getParentKey() + { + $id = $this->parent->getAttribute($this->localKey); + $this->related->setRelationCast($this->localKey); + if($this->related->hasCast($this->localKey, null,'set')){ + $id = $this->related->castAttribute($this->localKey, $id,'set'); + } + return $id; + } +} \ No newline at end of file From 879f087ea368470cb69e50bf33808d3d744c9ca2 Mon Sep 17 00:00:00 2001 From: hooman naghiee Date: Tue, 10 May 2016 12:48:17 +0430 Subject: [PATCH 07/88] set one and many relations to use HasOneOrManyTrait --- src/Jenssegers/Mongodb/Relations/HasMany.php | 2 ++ src/Jenssegers/Mongodb/Relations/HasOne.php | 2 ++ 2 files changed, 4 insertions(+) diff --git a/src/Jenssegers/Mongodb/Relations/HasMany.php b/src/Jenssegers/Mongodb/Relations/HasMany.php index 4a30e940f..c73b08157 100644 --- a/src/Jenssegers/Mongodb/Relations/HasMany.php +++ b/src/Jenssegers/Mongodb/Relations/HasMany.php @@ -5,6 +5,8 @@ class HasMany extends EloquentHasMany { + use HasOneOrManyTrait; + /** * Add the constraints for a relationship count query. * diff --git a/src/Jenssegers/Mongodb/Relations/HasOne.php b/src/Jenssegers/Mongodb/Relations/HasOne.php index c7a6ef41c..1252de7f2 100644 --- a/src/Jenssegers/Mongodb/Relations/HasOne.php +++ b/src/Jenssegers/Mongodb/Relations/HasOne.php @@ -5,6 +5,8 @@ class HasOne extends EloquentHasOne { + use HasOneOrManyTrait; + /** * Add the constraints for a relationship count query. * From c7f7f376c92ef9b11071b843f41168ffd4a5632d Mon Sep 17 00:00:00 2001 From: hooman naghiee Date: Tue, 10 May 2016 12:49:09 +0430 Subject: [PATCH 08/88] set test to run with use_mongo_id:true --- tests/config/database.php | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/tests/config/database.php b/tests/config/database.php index 4f70869c9..c61c72bb2 100644 --- a/tests/config/database.php +++ b/tests/config/database.php @@ -5,10 +5,11 @@ 'connections' => [ 'mongodb' => [ - 'name' => 'mongodb', - 'driver' => 'mongodb', - 'host' => '127.0.0.1', - 'database' => 'unittest', + 'name' => 'mongodb', + 'driver' => 'mongodb', + 'host' => '127.0.0.1', + 'database' => 'unittest', + 'use_mongo_id' => true, ], 'mysql' => [ From 427582e08d247bfa4d06a64023938655560a770f Mon Sep 17 00:00:00 2001 From: hooman naghiee Date: Tue, 10 May 2016 21:48:20 +0430 Subject: [PATCH 09/88] add morph one and many classes to make it use HasOneOrManyTrait --- src/Jenssegers/Mongodb/Eloquent/HybridRelations.php | 4 ++-- src/Jenssegers/Mongodb/Relations/MorphMany.php | 10 ++++++++++ src/Jenssegers/Mongodb/Relations/MorphOne.php | 10 ++++++++++ 3 files changed, 22 insertions(+), 2 deletions(-) create mode 100644 src/Jenssegers/Mongodb/Relations/MorphMany.php create mode 100644 src/Jenssegers/Mongodb/Relations/MorphOne.php diff --git a/src/Jenssegers/Mongodb/Eloquent/HybridRelations.php b/src/Jenssegers/Mongodb/Eloquent/HybridRelations.php index 66b425224..d39d4a6c7 100644 --- a/src/Jenssegers/Mongodb/Eloquent/HybridRelations.php +++ b/src/Jenssegers/Mongodb/Eloquent/HybridRelations.php @@ -1,13 +1,13 @@ Date: Tue, 10 May 2016 21:49:48 +0430 Subject: [PATCH 10/88] fix buildDictionary in EloquentMorphTo class and use HasOneOrManyTrait --- src/Jenssegers/Mongodb/Relations/MorphTo.php | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/src/Jenssegers/Mongodb/Relations/MorphTo.php b/src/Jenssegers/Mongodb/Relations/MorphTo.php index 3af336acd..a88437dc1 100644 --- a/src/Jenssegers/Mongodb/Relations/MorphTo.php +++ b/src/Jenssegers/Mongodb/Relations/MorphTo.php @@ -1,9 +1,12 @@ {$this->morphType}) { + $this->dictionary[$model->{$this->morphType}][(string)$model->{$this->foreignKey}][] = $model; + } + } + } + + /** * Get all of the relation results for a type. * From c5aef81f317d294700b9e369c766ff8c0a8e3758 Mon Sep 17 00:00:00 2001 From: hooman naghiee Date: Tue, 10 May 2016 21:50:13 +0430 Subject: [PATCH 11/88] cleanup Model class --- src/Jenssegers/Mongodb/Relations/HasOneOrManyTrait.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Jenssegers/Mongodb/Relations/HasOneOrManyTrait.php b/src/Jenssegers/Mongodb/Relations/HasOneOrManyTrait.php index 6248efebc..aa5a2606e 100644 --- a/src/Jenssegers/Mongodb/Relations/HasOneOrManyTrait.php +++ b/src/Jenssegers/Mongodb/Relations/HasOneOrManyTrait.php @@ -2,7 +2,6 @@ namespace Jenssegers\Mongodb\Relations; use Illuminate\Database\Eloquent\Collection; -use MongoDB\BSON\ObjectID; /** * Class HasOneOrManyTrait @@ -10,6 +9,7 @@ * * @property $this parent Jenssegers\Mongodb\Relations * @property $this localKey + * @property $this related */ trait HasOneOrManyTrait { From b886303f6f7e9425170fae13b7af82669755ed2d Mon Sep 17 00:00:00 2001 From: hooman naghiee Date: Tue, 10 May 2016 22:53:44 +0430 Subject: [PATCH 12/88] add useMongoId to check if driver uses mongoId in relations --- src/Jenssegers/Mongodb/Eloquent/Builder.php | 3 ++- src/Jenssegers/Mongodb/Eloquent/Model.php | 16 ++++++++++++++-- .../Mongodb/Relations/HasOneOrManyTrait.php | 15 ++++++++++++--- 3 files changed, 28 insertions(+), 6 deletions(-) diff --git a/src/Jenssegers/Mongodb/Eloquent/Builder.php b/src/Jenssegers/Mongodb/Eloquent/Builder.php index 2b888b8c9..43b88ef09 100644 --- a/src/Jenssegers/Mongodb/Eloquent/Builder.php +++ b/src/Jenssegers/Mongodb/Eloquent/Builder.php @@ -205,7 +205,8 @@ protected function addHasWhere(EloquentBuilder $hasQuery, Relation $relation, $o $relatedIds = array_map(function ($id) use ($relation) { $relationModel = $relation->getRelated(); $relationModel->setRelationCast($relation->getHasCompareKey()); - if($relationModel->hasCast($relation->getHasCompareKey(), null,'set')){ + if($relationModel->useMongoId() + && $relationModel->hasCast($relation->getHasCompareKey(), null,'set')){ $id = $relationModel->castAttribute($relation->getHasCompareKey(), $id,'set'); } return $id; diff --git a/src/Jenssegers/Mongodb/Eloquent/Model.php b/src/Jenssegers/Mongodb/Eloquent/Model.php index 8142c78cf..5f3d31507 100644 --- a/src/Jenssegers/Mongodb/Eloquent/Model.php +++ b/src/Jenssegers/Mongodb/Eloquent/Model.php @@ -580,6 +580,15 @@ public function hasCast($key, $types = null, $castType = 'get') return false; } + /** + * check if driver uses mongoId in relations. + * + * @return bool + */ + public function useMongoId() + { + return (bool)config('database.connections.mongodb.use_mongo_id', false); + } /** @@ -663,8 +672,11 @@ protected function asMongoDate($value) */ public function setRelationCast($key) { - $useMongoId = config('database.connections.mongodb.use_mongo_id',false); - if($useMongoId){ + if($key == '_id'){ + $this->saveCasts['_id'] = 'ObjectID'; + return; + } + if($this->useMongoId()){ if (ends_with($key, '_id')) { $this->saveCasts[$key] = 'ObjectID'; } diff --git a/src/Jenssegers/Mongodb/Relations/HasOneOrManyTrait.php b/src/Jenssegers/Mongodb/Relations/HasOneOrManyTrait.php index aa5a2606e..449023b6d 100644 --- a/src/Jenssegers/Mongodb/Relations/HasOneOrManyTrait.php +++ b/src/Jenssegers/Mongodb/Relations/HasOneOrManyTrait.php @@ -22,10 +22,17 @@ trait HasOneOrManyTrait */ protected function getKeys(array $models, $key = null) { + return array_unique(array_values(array_map(function ($model) use ($key) { - $model->setRelationCast($key); $id = $key ? $model->getAttribute($key) : $model->getKey(); - return $model->castAttribute($key, $id,'set'); + + if($this->related->useMongoId()){ + $model->setRelationCast($key); + + return $model->castAttribute($key, $id,'set'); + } + + return $id; }, $models))); } @@ -57,7 +64,9 @@ public function getParentKey() { $id = $this->parent->getAttribute($this->localKey); $this->related->setRelationCast($this->localKey); - if($this->related->hasCast($this->localKey, null,'set')){ + if($this->related->useMongoId() + && $this->related->hasCast($this->localKey, null,'set')){ + $id = $this->related->castAttribute($this->localKey, $id,'set'); } return $id; From d05d237cfe251f1d46c4455554827ff4255f248e Mon Sep 17 00:00:00 2001 From: hooman naghiee Date: Tue, 10 May 2016 22:55:40 +0430 Subject: [PATCH 13/88] add relation tests that tests new cast part --- phpunit.xml | 1 + tests/RelationsWithMongoIdTest.php | 530 +++++++++++++++++++++++++++++ 2 files changed, 531 insertions(+) create mode 100644 tests/RelationsWithMongoIdTest.php diff --git a/phpunit.xml b/phpunit.xml index 796bd5b38..7d8893a4b 100644 --- a/phpunit.xml +++ b/phpunit.xml @@ -36,6 +36,7 @@ tests/RelationsTest.php tests/EmbeddedRelationsTest.php + tests/RelationsWithMongoIdTest.php tests/RelationsTest.php diff --git a/tests/RelationsWithMongoIdTest.php b/tests/RelationsWithMongoIdTest.php new file mode 100644 index 000000000..f72f97dd7 --- /dev/null +++ b/tests/RelationsWithMongoIdTest.php @@ -0,0 +1,530 @@ +true]); + } + + public function tearDown() + { + Mockery::close(); + config(['database.connections.mongodb.use_mongo_id'=>false]); + + User::truncate(); + Client::truncate(); + Address::truncate(); + Book::truncate(); + Item::truncate(); + Role::truncate(); + Client::truncate(); + Group::truncate(); + Photo::truncate(); + } + + public function testHasMany() + { + $author = User::create(['name' => 'George R. R. Martin']); + Book::create(['title' => 'A Game of Thrones', 'author_id' => $author->_id]); + Book::create(['title' => 'A Clash of Kings', 'author_id' => $author->_id]); + + $books = $author->books; + $this->assertEquals(2, count($books)); + + $user = User::create(['name' => 'John Doe']); + Item::create(['type' => 'knife', 'user_id' => $user->_id]); + Item::create(['type' => 'shield', 'user_id' => $user->_id]); + Item::create(['type' => 'sword', 'user_id' => $user->_id]); + Item::create(['type' => 'bag', 'user_id' => null]); + + $items = $user->items; + $this->assertEquals(3, count($items)); + } + + public function testBelongsTo() + { + $user = User::create(['name' => 'George R. R. Martin']); + Book::create(['title' => 'A Game of Thrones', 'author_id' => $user->_id]); + $book = Book::create(['title' => 'A Clash of Kings', 'author_id' => $user->_id]); + + $author = $book->author; + $this->assertEquals('George R. R. Martin', $author->name); + + $user = User::create(['name' => 'John Doe']); + $item = Item::create(['type' => 'sword', 'user_id' => $user->_id]); + + $owner = $item->user; + $this->assertEquals('John Doe', $owner->name); + + $book = Book::create(['title' => 'A Clash of Kings']); + $this->assertEquals(null, $book->author); + } + + public function testHasOne() + { + $user = User::create(['name' => 'John Doe']); + Role::create(['type' => 'admin', 'user_id' => $user->_id]); + + $role = $user->role; + $this->assertEquals('admin', $role->type); + $this->assertEquals($user->_id, $role->user_id); + + $user = User::create(['name' => 'Jane Doe']); + $role = new Role(['type' => 'user']); + $user->role()->save($role); + + $role = $user->role; + $this->assertEquals('user', $role->type); + $this->assertEquals($user->_id, $role->user_id); + + $user = User::where('name', 'Jane Doe')->first(); + $role = $user->role; + $this->assertEquals('user', $role->type); + $this->assertEquals($user->_id, $role->user_id); + } + + public function testWithBelongsTo() + { + $user = User::create(['name' => 'John Doe']); + Item::create(['type' => 'knife', 'user_id' => $user->_id]); + Item::create(['type' => 'shield', 'user_id' => $user->_id]); + Item::create(['type' => 'sword', 'user_id' => $user->_id]); + Item::create(['type' => 'bag', 'user_id' => null]); + + $items = Item::with('user')->orderBy('user_id', 'desc')->get(); + + $user = $items[0]->getRelation('user'); + $this->assertInstanceOf('User', $user); + $this->assertEquals('John Doe', $user->name); + $this->assertEquals(1, count($items[0]->getRelations())); + $this->assertEquals(null, $items[3]->getRelation('user')); + } + + public function testWithHashMany() + { + $user = User::create(['name' => 'John Doe']); + Item::create(['type' => 'knife', 'user_id' => $user->_id]); + Item::create(['type' => 'shield', 'user_id' => $user->_id]); + Item::create(['type' => 'sword', 'user_id' => $user->_id]); + Item::create(['type' => 'bag', 'user_id' => null]); + + $user = User::with('items')->find($user->_id); + + $items = $user->getRelation('items'); + $this->assertEquals(3, count($items)); + $this->assertInstanceOf('Item', $items[0]); + } + + public function testWithHasOne() + { + $user = User::create(['name' => 'John Doe']); + Role::create(['type' => 'admin', 'user_id' => $user->_id]); + Role::create(['type' => 'guest', 'user_id' => $user->_id]); + + $user = User::with('role')->find($user->_id); + + $role = $user->getRelation('role'); + $this->assertInstanceOf('Role', $role); + $this->assertEquals('admin', $role->type); + } + + public function testEasyRelation() + { + // Has Many + $user = User::create(['name' => 'John Doe']); + $item = Item::create(['type' => 'knife']); + $user->items()->save($item); + + $user = User::find($user->_id); + $items = $user->items; + $this->assertEquals(1, count($items)); + $this->assertInstanceOf('Item', $items[0]); + $this->assertEquals($user->_id, $items[0]->user_id); + + // Has one + $user = User::create(['name' => 'John Doe']); + $role = Role::create(['type' => 'admin']); + $user->role()->save($role); + + $user = User::find($user->_id); + $role = $user->role; + $this->assertInstanceOf('Role', $role); + $this->assertEquals('admin', $role->type); + $this->assertEquals($user->_id, $role->user_id); + } + + public function testBelongsToMany() + { + $user = User::create(['name' => 'John Doe']); + + // Add 2 clients + $user->clients()->save(new Client(['name' => 'Pork Pies Ltd.'])); + $user->clients()->create(['name' => 'Buffet Bar Inc.']); + + // Refetch + $user = User::with('clients')->find($user->_id); + $client = Client::with('users')->first(); + + // Check for relation attributes + $this->assertTrue(array_key_exists('user_ids', $client->getAttributes())); + $this->assertTrue(array_key_exists('client_ids', $user->getAttributes())); + + $clients = $user->getRelation('clients'); + $users = $client->getRelation('users'); + + $this->assertInstanceOf('Illuminate\Database\Eloquent\Collection', $users); + $this->assertInstanceOf('Illuminate\Database\Eloquent\Collection', $clients); + $this->assertInstanceOf('Client', $clients[0]); + $this->assertInstanceOf('User', $users[0]); + $this->assertCount(2, $user->clients); + $this->assertCount(1, $client->users); + + // Now create a new user to an existing client + $user = $client->users()->create(['name' => 'Jane Doe']); + + $this->assertInstanceOf('Illuminate\Database\Eloquent\Collection', $user->clients); + $this->assertInstanceOf('Client', $user->clients->first()); + $this->assertCount(1, $user->clients); + + // Get user and unattached client + $user = User::where('name', '=', 'Jane Doe')->first(); + $client = Client::Where('name', '=', 'Buffet Bar Inc.')->first(); + + // Check the models are what they should be + $this->assertInstanceOf('Client', $client); + $this->assertInstanceOf('User', $user); + + // Assert they are not attached + $this->assertFalse(in_array($client->_id, $user->client_ids)); + $this->assertFalse(in_array($user->_id, $client->user_ids)); + $this->assertCount(1, $user->clients); + $this->assertCount(1, $client->users); + + // Attach the client to the user + $user->clients()->attach($client); + + // Get the new user model + $user = User::where('name', '=', 'Jane Doe')->first(); + $client = Client::Where('name', '=', 'Buffet Bar Inc.')->first(); + + // Assert they are attached + $this->assertTrue(in_array($client->_id, $user->client_ids)); + $this->assertTrue(in_array($user->_id, $client->user_ids)); + $this->assertCount(2, $user->clients); + $this->assertCount(2, $client->users); + + // Detach clients from user + $user->clients()->sync([]); + + // Get the new user model + $user = User::where('name', '=', 'Jane Doe')->first(); + $client = Client::Where('name', '=', 'Buffet Bar Inc.')->first(); + + // Assert they are not attached + $this->assertFalse(in_array($client->_id, $user->client_ids)); + $this->assertFalse(in_array($user->_id, $client->user_ids)); + $this->assertCount(0, $user->clients); + $this->assertCount(1, $client->users); + } + + public function testBelongsToManyAttachesExistingModels() + { + $user = User::create(['name' => 'John Doe', 'client_ids' => ['1234523']]); + + $clients = [ + Client::create(['name' => 'Pork Pies Ltd.'])->_id, + Client::create(['name' => 'Buffet Bar Inc.'])->_id, + ]; + + $moreClients = [ + Client::create(['name' => 'synced Boloni Ltd.'])->_id, + Client::create(['name' => 'synced Meatballs Inc.'])->_id, + ]; + + // Sync multiple records + $user->clients()->sync($clients); + + $user = User::with('clients')->find($user->_id); + + // Assert non attached ID's are detached succesfully + $this->assertFalse(in_array('1234523', $user->client_ids)); + + // Assert there are two client objects in the relationship + $this->assertCount(2, $user->clients); + + // Add more clients + $user->clients()->sync($moreClients); + + // Refetch + $user = User::with('clients')->find($user->_id); + + // Assert there are now still 2 client objects in the relationship + $this->assertCount(2, $user->clients); + + // Assert that the new relationships name start with synced + $this->assertStringStartsWith('synced', $user->clients[0]->name); + $this->assertStringStartsWith('synced', $user->clients[1]->name); + } + + public function testBelongsToManySync() + { + // create test instances + $user = User::create(['name' => 'John Doe']); + $client1 = Client::create(['name' => 'Pork Pies Ltd.'])->_id; + $client2 = Client::create(['name' => 'Buffet Bar Inc.'])->_id; + + // Sync multiple + $user->clients()->sync([$client1, $client2]); + $this->assertCount(2, $user->clients); + + // Refresh user + $user = User::where('name', '=', 'John Doe')->first(); + + // Sync single + $user->clients()->sync([$client1]); + $this->assertCount(1, $user->clients); + } + + public function testBelongsToManyAttachArray() + { + $user = User::create(['name' => 'John Doe']); + $client1 = Client::create(['name' => 'Test 1'])->_id; + $client2 = Client::create(['name' => 'Test 2'])->_id; + + $user = User::where('name', '=', 'John Doe')->first(); + $user->clients()->attach([$client1, $client2]); + $this->assertCount(2, $user->clients); + } + + public function testBelongsToManySyncAlreadyPresent() + { + $user = User::create(['name' => 'John Doe']); + $client1 = Client::create(['name' => 'Test 1'])->_id; + $client2 = Client::create(['name' => 'Test 2'])->_id; + + $user->clients()->sync([$client1, $client2]); + $this->assertCount(2, $user->clients); + + $user = User::where('name', '=', 'John Doe')->first(); + $user->clients()->sync([$client1]); + $this->assertCount(1, $user->clients); + + $user = User::where('name', '=', 'John Doe')->first()->toArray(); + $this->assertCount(1, $user['client_ids']); + } + + public function testBelongsToManyCustom() + { + $user = User::create(['name' => 'John Doe']); + $group = $user->groups()->create(['name' => 'Admins']); + + // Refetch + $user = User::find($user->_id); + $group = Group::find($group->_id); + + // Check for custom relation attributes + $this->assertTrue(array_key_exists('users', $group->getAttributes())); + $this->assertTrue(array_key_exists('groups', $user->getAttributes())); + + // Assert they are attached + $this->assertTrue(in_array($group->_id, $user->groups)); + $this->assertTrue(in_array($user->_id, $group->users)); + $this->assertEquals($group->_id, $user->groups()->first()->_id); + $this->assertEquals($user->_id, $group->users()->first()->_id); + } + + public function testMorph() + { + $user = User::create(['name' => 'John Doe']); + $client = Client::create(['name' => 'Jane Doe']); + + $photo = Photo::create(['url' => 'http://graph.facebook.com/john.doe/picture']); + $photo = $user->photos()->save($photo); + + $this->assertEquals(1, $user->photos->count()); + $this->assertEquals($photo->id, $user->photos->first()->id); + + $user = User::find($user->_id); + $this->assertEquals(1, $user->photos->count()); + $this->assertEquals($photo->id, $user->photos->first()->id); + + $photo = Photo::create(['url' => 'http://graph.facebook.com/jane.doe/picture']); + $client->photo()->save($photo); + + $this->assertNotNull($client->photo); + $this->assertEquals($photo->id, $client->photo->id); + + $client = Client::find($client->_id); + $this->assertNotNull($client->photo); + $this->assertEquals($photo->id, $client->photo->id); + + $photo = Photo::first(); + $this->assertEquals($photo->imageable->name, $user->name); + + $user = User::with('photos')->find($user->_id); + $relations = $user->getRelations(); + $this->assertTrue(array_key_exists('photos', $relations)); + $this->assertEquals(1, $relations['photos']->count()); + + $photos = Photo::with('imageable')->get(); + $relations = $photos[0]->getRelations(); + $this->assertTrue(array_key_exists('imageable', $relations)); + $this->assertInstanceOf('User', $photos[0]->imageable); + + $relations = $photos[1]->getRelations(); + $this->assertTrue(array_key_exists('imageable', $relations)); + $this->assertInstanceOf('Client', $photos[1]->imageable); + } + + public function testHasManyHas() + { + $author1 = User::create(['name' => 'George R. R. Martin']); + $author1->books()->create(['title' => 'A Game of Thrones', 'rating' => 5]); + $author1->books()->create(['title' => 'A Clash of Kings', 'rating' => 5]); + $author2 = User::create(['name' => 'John Doe']); + $author2->books()->create(['title' => 'My book', 'rating' => 2]); + User::create(['name' => 'Anonymous author']); + Book::create(['title' => 'Anonymous book', 'rating' => 1]); + + $authors = User::has('books')->get(); + $this->assertCount(2, $authors); + $this->assertEquals('George R. R. Martin', $authors[0]->name); + $this->assertEquals('John Doe', $authors[1]->name); + + $authors = User::has('books', '>', 1)->get(); + $this->assertCount(1, $authors); + + $authors = User::has('books', '<', 5)->get(); + $this->assertCount(3, $authors); + + $authors = User::has('books', '>=', 2)->get(); + $this->assertCount(1, $authors); + + $authors = User::has('books', '<=', 1)->get(); + $this->assertCount(2, $authors); + + $authors = User::has('books', '=', 2)->get(); + $this->assertCount(1, $authors); + + $authors = User::has('books', '!=', 2)->get(); + $this->assertCount(2, $authors); + + $authors = User::has('books', '=', 0)->get(); + $this->assertCount(1, $authors); + + $authors = User::has('books', '!=', 0)->get(); + $this->assertCount(2, $authors); + + $authors = User::whereHas('books', function ($query) { + $query->where('rating', 5); + + })->get(); + $this->assertCount(1, $authors); + + $authors = User::whereHas('books', function ($query) { + $query->where('rating', '<', 5); + + })->get(); + $this->assertCount(1, $authors); + } + + public function testHasOneHas() + { + $user1 = User::create(['name' => 'John Doe']); + $user1->role()->create(['title' => 'admin']); + $user2 = User::create(['name' => 'Jane Doe']); + $user2->role()->create(['title' => 'reseller']); + User::create(['name' => 'Mark Moe']); + Role::create(['title' => 'Customer']); + + $users = User::has('role')->get(); + $this->assertCount(2, $users); + $this->assertEquals('John Doe', $users[0]->name); + $this->assertEquals('Jane Doe', $users[1]->name); + + $users = User::has('role', '=', 0)->get(); + $this->assertCount(1, $users); + + $users = User::has('role', '!=', 0)->get(); + $this->assertCount(2, $users); + } + + public function testNestedKeys() + { + $client = Client::create([ + 'data' => [ + 'client_id' => 35298, + 'name' => 'John Doe', + ], + ]); + + $address = $client->addresses()->create([ + 'data' => [ + 'address_id' => 1432, + 'city' => 'Paris', + ], + ]); + + $client = Client::where('data.client_id', 35298)->first(); + $this->assertEquals(1, $client->addresses->count()); + + $address = $client->addresses->first(); + $this->assertEquals('Paris', $address->data['city']); + + $client = Client::with('addresses')->first(); + $this->assertEquals('Paris', $client->addresses->first()->data['city']); + } + + public function testDoubleSaveOneToMany() + { + $author = User::create(['name' => 'George R. R. Martin']); + $book = Book::create(['title' => 'A Game of Thrones']); + + $author->books()->save($book); + $author->books()->save($book); + $author->save(); + $this->assertEquals(1, $author->books()->count()); + $this->assertEquals($author->_id, $book->author_id); + + $author = User::where('name', 'George R. R. Martin')->first(); + $book = Book::where('title', 'A Game of Thrones')->first(); + $this->assertEquals(1, $author->books()->count()); + $this->assertEquals($author->_id, $book->author_id); + + $author->books()->save($book); + $author->books()->save($book); + $author->save(); + $this->assertEquals(1, $author->books()->count()); + $this->assertEquals($author->_id, $book->author_id); + } + + public function testDoubleSaveManyToMany() + { + $user = User::create(['name' => 'John Doe']); + $client = Client::create(['name' => 'Admins']); + + $user->clients()->save($client); + $user->clients()->save($client); + $user->save(); + + $this->assertEquals(1, $user->clients()->count()); + $this->assertEquals([$user->_id], $client->user_ids); + $this->assertEquals([$client->_id], $user->client_ids); + + $user = User::where('name', 'John Doe')->first(); + $client = Client::where('name', 'Admins')->first(); + $this->assertEquals(1, $user->clients()->count()); + $this->assertEquals([$user->_id], $client->user_ids); + $this->assertEquals([$client->_id], $user->client_ids); + + $user->clients()->save($client); + $user->clients()->save($client); + $user->save(); + $this->assertEquals(1, $user->clients()->count()); + $this->assertEquals([$user->_id], $client->user_ids); + $this->assertEquals([$client->_id], $user->client_ids); + } +} From dd6923ed95e8d092b477c2640d428f05ae09a388 Mon Sep 17 00:00:00 2001 From: hooman naghiee Date: Tue, 10 May 2016 23:37:39 +0430 Subject: [PATCH 14/88] cleanup the code --- src/Jenssegers/Mongodb/Eloquent/Builder.php | 9 ++++---- src/Jenssegers/Mongodb/Eloquent/Model.php | 22 +++++++++---------- .../Mongodb/Relations/BelongsTo.php | 4 ++-- .../Mongodb/Relations/HasOneOrManyTrait.php | 16 ++++++-------- .../Mongodb/Relations/MorphMany.php | 3 +-- src/Jenssegers/Mongodb/Relations/MorphOne.php | 3 +-- src/Jenssegers/Mongodb/Relations/MorphTo.php | 3 +-- tests/RelationsWithMongoIdTest.php | 4 ++-- 8 files changed, 28 insertions(+), 36 deletions(-) diff --git a/src/Jenssegers/Mongodb/Eloquent/Builder.php b/src/Jenssegers/Mongodb/Eloquent/Builder.php index 43b88ef09..6155afb7a 100644 --- a/src/Jenssegers/Mongodb/Eloquent/Builder.php +++ b/src/Jenssegers/Mongodb/Eloquent/Builder.php @@ -169,7 +169,7 @@ protected function addHasWhere(EloquentBuilder $hasQuery, Relation $relation, $o // Get the number of related objects for each possible parent. $compareKeys = $query->pluck($relation->getHasCompareKey()); $compareKeys = array_map(function ($id) { - return (string)$id; + return (string) $id; }, $compareKeys); $relationCount = array_count_values($compareKeys); @@ -205,14 +205,13 @@ protected function addHasWhere(EloquentBuilder $hasQuery, Relation $relation, $o $relatedIds = array_map(function ($id) use ($relation) { $relationModel = $relation->getRelated(); $relationModel->setRelationCast($relation->getHasCompareKey()); - if($relationModel->useMongoId() - && $relationModel->hasCast($relation->getHasCompareKey(), null,'set')){ - $id = $relationModel->castAttribute($relation->getHasCompareKey(), $id,'set'); + if ($relationModel->useMongoId() + && $relationModel->hasCast($relation->getHasCompareKey(), null, 'set')) { + $id = $relationModel->castAttribute($relation->getHasCompareKey(), $id, 'set'); } return $id; }, array_keys($relationCount)); - // Add whereIn to the query. return $this->whereIn($this->model->getKeyName(), $relatedIds, $boolean, $not); } diff --git a/src/Jenssegers/Mongodb/Eloquent/Model.php b/src/Jenssegers/Mongodb/Eloquent/Model.php index 5f3d31507..f2a3f41a2 100644 --- a/src/Jenssegers/Mongodb/Eloquent/Model.php +++ b/src/Jenssegers/Mongodb/Eloquent/Model.php @@ -45,7 +45,6 @@ abstract class Model extends BaseModel */ protected $saveCasts = []; - /** * Custom accessor for the model's id. * @@ -290,7 +289,7 @@ public function setAttribute($key, $value) // cast data for saving. // set _id to converted into ObjectID if its possible. $this->setRelationCast($key); - $value = $this->castAttribute($key, $value,'set'); + $value = $this->castAttribute($key, $value, 'set'); // Support keys in dot notation. if (str_contains($key, '.')) { @@ -575,7 +574,7 @@ protected function getCastType($key, $castType = 'get') public function hasCast($key, $types = null, $castType = 'get') { if (array_key_exists($key, $this->getCasts($castType))) { - return $types ? in_array($this->getCastType($key, $castType), (array)$types, true) : true; + return $types ? in_array($this->getCastType($key, $castType), (array) $types, true) : true; } return false; @@ -587,10 +586,9 @@ public function hasCast($key, $types = null, $castType = 'get') */ public function useMongoId() { - return (bool)config('database.connections.mongodb.use_mongo_id', false); + return (bool) config('database.connections.mongodb.use_mongo_id', false); } - /** * Cast an attribute to a mongo type. * @@ -602,7 +600,7 @@ public function useMongoId() public function castAttribute($key, $value, $castType = 'get') { if (is_null($value)) { - return null; + return; } if (!$this->hasCast($key, null, $castType)) { @@ -612,16 +610,16 @@ public function castAttribute($key, $value, $castType = 'get') switch ($this->getCastType($key, $castType)) { case 'int': case 'integer': - return (int)$value; + return (int) $value; case 'real': case 'float': case 'double': - return (float)$value; + return (float) $value; case 'string': - return (string)$value; + return (string) $value; case 'bool': case 'boolean': - return (bool)$value; + return (bool) $value; case 'date': case 'utcdatetime': case 'mongodate': @@ -672,11 +670,11 @@ protected function asMongoDate($value) */ public function setRelationCast($key) { - if($key == '_id'){ + if ($key == '_id') { $this->saveCasts['_id'] = 'ObjectID'; return; } - if($this->useMongoId()){ + if ($this->useMongoId()) { if (ends_with($key, '_id')) { $this->saveCasts[$key] = 'ObjectID'; } diff --git a/src/Jenssegers/Mongodb/Relations/BelongsTo.php b/src/Jenssegers/Mongodb/Relations/BelongsTo.php index d424f7063..c12402cc2 100644 --- a/src/Jenssegers/Mongodb/Relations/BelongsTo.php +++ b/src/Jenssegers/Mongodb/Relations/BelongsTo.php @@ -53,8 +53,8 @@ public function match(array $models, \Illuminate\Database\Eloquent\Collection $r // and match back onto their children using these keys of the dictionary and // the primary key of the children to map them onto the correct instances. foreach ($models as $model) { - if (isset($dictionary[(string)$model->$foreign])) { - $model->setRelation($relation, $dictionary[(string)$model->$foreign]); + if (isset($dictionary[(string) $model->$foreign])) { + $model->setRelation($relation, $dictionary[(string) $model->$foreign]); } } return $models; diff --git a/src/Jenssegers/Mongodb/Relations/HasOneOrManyTrait.php b/src/Jenssegers/Mongodb/Relations/HasOneOrManyTrait.php index 449023b6d..1aa5c12fa 100644 --- a/src/Jenssegers/Mongodb/Relations/HasOneOrManyTrait.php +++ b/src/Jenssegers/Mongodb/Relations/HasOneOrManyTrait.php @@ -22,14 +22,13 @@ trait HasOneOrManyTrait */ protected function getKeys(array $models, $key = null) { - return array_unique(array_values(array_map(function ($model) use ($key) { $id = $key ? $model->getAttribute($key) : $model->getKey(); - if($this->related->useMongoId()){ + if ($this->related->useMongoId()) { $model->setRelationCast($key); - return $model->castAttribute($key, $id,'set'); + return $model->castAttribute($key, $id, 'set'); } return $id; @@ -50,7 +49,7 @@ protected function buildDictionary(Collection $results) // relationship as this will allow us to quickly access all of the related // models without having to do nested looping which will be quite slow. foreach ($results as $result) { - $dictionary[(string)$result->{$foreign}][] = $result; + $dictionary[(string) $result->{$foreign}][] = $result; } return $dictionary; } @@ -64,11 +63,10 @@ public function getParentKey() { $id = $this->parent->getAttribute($this->localKey); $this->related->setRelationCast($this->localKey); - if($this->related->useMongoId() - && $this->related->hasCast($this->localKey, null,'set')){ - - $id = $this->related->castAttribute($this->localKey, $id,'set'); + if ($this->related->useMongoId() + && $this->related->hasCast($this->localKey, null, 'set')) { + $id = $this->related->castAttribute($this->localKey, $id, 'set'); } return $id; } -} \ No newline at end of file +} diff --git a/src/Jenssegers/Mongodb/Relations/MorphMany.php b/src/Jenssegers/Mongodb/Relations/MorphMany.php index a1d9364be..009bb630d 100644 --- a/src/Jenssegers/Mongodb/Relations/MorphMany.php +++ b/src/Jenssegers/Mongodb/Relations/MorphMany.php @@ -6,5 +6,4 @@ class MorphMany extends EloquentMorphMany { use HasOneOrManyTrait; - -} \ No newline at end of file +} diff --git a/src/Jenssegers/Mongodb/Relations/MorphOne.php b/src/Jenssegers/Mongodb/Relations/MorphOne.php index e70a9bd6a..9163dd5a4 100644 --- a/src/Jenssegers/Mongodb/Relations/MorphOne.php +++ b/src/Jenssegers/Mongodb/Relations/MorphOne.php @@ -6,5 +6,4 @@ class MorphOne extends EloquentMorphOne { use HasOneOrManyTrait; - -} \ No newline at end of file +} diff --git a/src/Jenssegers/Mongodb/Relations/MorphTo.php b/src/Jenssegers/Mongodb/Relations/MorphTo.php index a88437dc1..d4354f021 100644 --- a/src/Jenssegers/Mongodb/Relations/MorphTo.php +++ b/src/Jenssegers/Mongodb/Relations/MorphTo.php @@ -30,12 +30,11 @@ protected function buildDictionary(Collection $models) { foreach ($models as $model) { if ($model->{$this->morphType}) { - $this->dictionary[$model->{$this->morphType}][(string)$model->{$this->foreignKey}][] = $model; + $this->dictionary[$model->{$this->morphType}][(string) $model->{$this->foreignKey}][] = $model; } } } - /** * Get all of the relation results for a type. * diff --git a/tests/RelationsWithMongoIdTest.php b/tests/RelationsWithMongoIdTest.php index f72f97dd7..224b5e93f 100644 --- a/tests/RelationsWithMongoIdTest.php +++ b/tests/RelationsWithMongoIdTest.php @@ -6,13 +6,13 @@ class RelationsWithMongoIdTest extends TestCase public function setUp() { parent::setUp(); // TODO: Change the autogenerated stub - config(['database.connections.mongodb.use_mongo_id'=>true]); + config(['database.connections.mongodb.use_mongo_id' => true]); } public function tearDown() { Mockery::close(); - config(['database.connections.mongodb.use_mongo_id'=>false]); + config(['database.connections.mongodb.use_mongo_id' => false]); User::truncate(); Client::truncate(); From dbbab066b35ec10e8f59e2842fdd95dea46fea38 Mon Sep 17 00:00:00 2001 From: hooman naghiee Date: Wed, 11 May 2016 00:23:44 +0430 Subject: [PATCH 15/88] add setter for casts --- src/Jenssegers/Mongodb/Eloquent/Model.php | 17 ++++++++++- tests/RelationsWithMongoIdTest.php | 36 +++++++++++++++++++++++ 2 files changed, 52 insertions(+), 1 deletion(-) diff --git a/src/Jenssegers/Mongodb/Eloquent/Model.php b/src/Jenssegers/Mongodb/Eloquent/Model.php index f2a3f41a2..3707c86cb 100644 --- a/src/Jenssegers/Mongodb/Eloquent/Model.php +++ b/src/Jenssegers/Mongodb/Eloquent/Model.php @@ -537,6 +537,21 @@ public function __call($method, $parameters) return parent::__call($method, $parameters); } + /** + * setter for casts + * @param $cast + * @param string $castType + * @return void + */ + public function setCasts($cast, $castType = 'get') + { + if ($castType == 'set') { + $this->saveCasts = $cast; + return; + } + $this->casts = $cast; + } + /** * Get the casts array. * @@ -600,7 +615,7 @@ public function useMongoId() public function castAttribute($key, $value, $castType = 'get') { if (is_null($value)) { - return; + return null; } if (!$this->hasCast($key, null, $castType)) { diff --git a/tests/RelationsWithMongoIdTest.php b/tests/RelationsWithMongoIdTest.php index 224b5e93f..8e78bf592 100644 --- a/tests/RelationsWithMongoIdTest.php +++ b/tests/RelationsWithMongoIdTest.php @@ -527,4 +527,40 @@ public function testDoubleSaveManyToMany() $this->assertEquals([$user->_id], $client->user_ids); $this->assertEquals([$client->_id], $user->client_ids); } + + public function testCastAttribute() + { + $user = new User; + $user->setCasts([ + 'last_seen' => 'UTCDatetime', + 'age'=>'int', + 'name'=>'string', + 'rate'=>'float', + 'birthday'=>'timestamp', + 'isActive'=>'bool', + 'default'=>'default', + ], 'set'); + $user->setCasts([ + 'name'=>'string', + ]); + $carbon = Carbon\Carbon::now(); + $UTCDateTime = new \MongoDB\BSON\UTCDateTime($carbon->timestamp * 1000); + $test = $user->castAttribute('last_seen', $carbon, 'set'); + $this->assertEquals($UTCDateTime, $test); + $test = $user->castAttribute('last_seen', $UTCDateTime, 'set'); + $this->assertEquals($UTCDateTime, $test); + $test = $user->castAttribute('age', '1', 'set'); + $this->assertEquals(1, $test); + $test = $user->castAttribute('name', 40000, 'set'); + $this->assertEquals('40000', $test); + $test = $user->castAttribute('rate', '3.14', 'set'); + $this->assertEquals(3.14, $test); + $test = $user->castAttribute('birthday', $carbon, 'set'); + $this->assertEquals($carbon->timestamp, $test); + $test = $user->castAttribute('isActive', 1, 'set'); + $this->assertEquals(true, $test); + $test = $user->castAttribute('default', 'test', 'set'); + $this->assertEquals('test', $test); + } + } From 1bf882fac806f0044471a64fa6827d0f2844e61a Mon Sep 17 00:00:00 2001 From: hooman naghiee Date: Wed, 11 May 2016 00:30:52 +0430 Subject: [PATCH 16/88] cleanup --- patch.txt | 46 +++++++++++++++++++++++ src/Jenssegers/Mongodb/Eloquent/Model.php | 2 +- tests/RelationsWithMongoIdTest.php | 15 ++++---- 3 files changed, 54 insertions(+), 9 deletions(-) create mode 100644 patch.txt diff --git a/patch.txt b/patch.txt new file mode 100644 index 000000000..e04703cc8 --- /dev/null +++ b/patch.txt @@ -0,0 +1,46 @@ +diff --git a/src/Jenssegers/Mongodb/Eloquent/Model.php b/src/Jenssegers/Mongodb/Eloquent/Model.php +index 3707c86cb7f732c97908d8ca3754118f4256e422..4a17b0f8c045b2d02f3f834ae0b207dccd2be311 100644 +--- a/src/Jenssegers/Mongodb/Eloquent/Model.php ++++ b/src/Jenssegers/Mongodb/Eloquent/Model.php +@@ -615,7 +615,7 @@ abstract class Model extends BaseModel + public function castAttribute($key, $value, $castType = 'get') + { + if (is_null($value)) { +- return null; ++ return; + } + + if (!$this->hasCast($key, null, $castType)) { +diff --git a/tests/RelationsWithMongoIdTest.php b/tests/RelationsWithMongoIdTest.php +index 8e78bf592b016b7a85609e699c6f0fa24c55dc0e..517c3be993b8eb68bae2349a061c6677be3cbfa7 100644 +--- a/tests/RelationsWithMongoIdTest.php ++++ b/tests/RelationsWithMongoIdTest.php +@@ -533,15 +533,15 @@ class RelationsWithMongoIdTest extends TestCase + $user = new User; + $user->setCasts([ + 'last_seen' => 'UTCDatetime', +- 'age'=>'int', +- 'name'=>'string', +- 'rate'=>'float', +- 'birthday'=>'timestamp', +- 'isActive'=>'bool', +- 'default'=>'default', ++ 'age' => 'int', ++ 'name' => 'string', ++ 'rate' => 'float', ++ 'birthday' => 'timestamp', ++ 'isActive' => 'bool', ++ 'default' => 'default', + ], 'set'); + $user->setCasts([ +- 'name'=>'string', ++ 'name' => 'string', + ]); + $carbon = Carbon\Carbon::now(); + $UTCDateTime = new \MongoDB\BSON\UTCDateTime($carbon->timestamp * 1000); +@@ -562,5 +562,4 @@ class RelationsWithMongoIdTest extends TestCase + $test = $user->castAttribute('default', 'test', 'set'); + $this->assertEquals('test', $test); + } +- + } diff --git a/src/Jenssegers/Mongodb/Eloquent/Model.php b/src/Jenssegers/Mongodb/Eloquent/Model.php index 3707c86cb..4a17b0f8c 100644 --- a/src/Jenssegers/Mongodb/Eloquent/Model.php +++ b/src/Jenssegers/Mongodb/Eloquent/Model.php @@ -615,7 +615,7 @@ public function useMongoId() public function castAttribute($key, $value, $castType = 'get') { if (is_null($value)) { - return null; + return; } if (!$this->hasCast($key, null, $castType)) { diff --git a/tests/RelationsWithMongoIdTest.php b/tests/RelationsWithMongoIdTest.php index 8e78bf592..517c3be99 100644 --- a/tests/RelationsWithMongoIdTest.php +++ b/tests/RelationsWithMongoIdTest.php @@ -533,15 +533,15 @@ public function testCastAttribute() $user = new User; $user->setCasts([ 'last_seen' => 'UTCDatetime', - 'age'=>'int', - 'name'=>'string', - 'rate'=>'float', - 'birthday'=>'timestamp', - 'isActive'=>'bool', - 'default'=>'default', + 'age' => 'int', + 'name' => 'string', + 'rate' => 'float', + 'birthday' => 'timestamp', + 'isActive' => 'bool', + 'default' => 'default', ], 'set'); $user->setCasts([ - 'name'=>'string', + 'name' => 'string', ]); $carbon = Carbon\Carbon::now(); $UTCDateTime = new \MongoDB\BSON\UTCDateTime($carbon->timestamp * 1000); @@ -562,5 +562,4 @@ public function testCastAttribute() $test = $user->castAttribute('default', 'test', 'set'); $this->assertEquals('test', $test); } - } From 324d4f9e1b0191b5fa6d06fb680a9b3de4ea281f Mon Sep 17 00:00:00 2001 From: Pooya Parsa Date: Fri, 26 Aug 2016 02:26:07 +0430 Subject: [PATCH 17/88] Filling with Dot-Notation Keys Simply override `removeTableFromKey($key)` method and just return original keys in order to support dot-notation when calling `fill` on model. --- src/Jenssegers/Mongodb/Eloquent/Model.php | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/src/Jenssegers/Mongodb/Eloquent/Model.php b/src/Jenssegers/Mongodb/Eloquent/Model.php index 797f1907f..bbbc2bcd8 100644 --- a/src/Jenssegers/Mongodb/Eloquent/Model.php +++ b/src/Jenssegers/Mongodb/Eloquent/Model.php @@ -535,6 +535,17 @@ protected function newBaseQueryBuilder() return new QueryBuilder($connection, $connection->getPostProcessor()); } + + /** + * We just return original key here in order to support keys in dot-notation + * + * @param string $key + * @return string + */ + protected function removeTableFromKey($key) + { + return $key; + } /** * Handle dynamic method calls into the method. From f1f58955dba44b9d164b03c686eda661b169520c Mon Sep 17 00:00:00 2001 From: Pooya Parsa Date: Fri, 26 Aug 2016 02:29:35 +0430 Subject: [PATCH 18/88] Style CI --- src/Jenssegers/Mongodb/Eloquent/Model.php | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/src/Jenssegers/Mongodb/Eloquent/Model.php b/src/Jenssegers/Mongodb/Eloquent/Model.php index bbbc2bcd8..22d36abed 100644 --- a/src/Jenssegers/Mongodb/Eloquent/Model.php +++ b/src/Jenssegers/Mongodb/Eloquent/Model.php @@ -537,11 +537,11 @@ protected function newBaseQueryBuilder() } /** - * We just return original key here in order to support keys in dot-notation - * - * @param string $key - * @return string - */ + * We just return original key here in order to support keys in dot-notation + * + * @param string $key + * @return string + */ protected function removeTableFromKey($key) { return $key; From 039458d9db9fbd71617e8e5eaf907416853283a6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fiete=20B=C3=B6rner?= Date: Wed, 10 Aug 2016 22:45:03 +0200 Subject: [PATCH 19/88] add sub document aggregation array functionality example: Model::sum('subarray.*.price'); this method is much simpler as to use as complex raw aggregations for this function a $unwind directive will be pushed in pipeline before $group --- src/Jenssegers/Mongodb/Query/Builder.php | 14 ++++++++++++++ tests/QueryBuilderTest.php | 16 ++++++++++++++++ 2 files changed, 30 insertions(+) diff --git a/src/Jenssegers/Mongodb/Query/Builder.php b/src/Jenssegers/Mongodb/Query/Builder.php index 74b9ee3a6..4aceeb421 100644 --- a/src/Jenssegers/Mongodb/Query/Builder.php +++ b/src/Jenssegers/Mongodb/Query/Builder.php @@ -187,6 +187,7 @@ public function getFresh($columns = []) // Use MongoDB's aggregation framework when using grouping or aggregation functions. if ($this->groups or $this->aggregate or $this->paginating) { $group = []; + $unwinds = []; // Add grouping columns to the $group part of the aggregation pipeline. if ($this->groups) { @@ -212,6 +213,13 @@ public function getFresh($columns = []) $function = $this->aggregate['function']; foreach ($this->aggregate['columns'] as $column) { + // Add unwind if a subdocument array should be aggregated + // column: subarray.price => {$unwind: '$subarray'} + if (count($splitColumns = explode('.*.', $column)) == 2) { + $unwinds[] = $splitColumns[0]; + $column = implode('.', $splitColumns); + } + // Translate count into sum. if ($function == 'count') { $group['aggregate'] = ['$sum' => 1]; @@ -241,6 +249,12 @@ public function getFresh($columns = []) if ($wheres) { $pipeline[] = ['$match' => $wheres]; } + + // apply unwinds for subdocument array aggregation + foreach($unwinds as $unwind){ + $pipeline[] = ['$unwind' => '$' . $unwind]; + } + if ($group) { $pipeline[] = ['$group' => $group]; } diff --git a/tests/QueryBuilderTest.php b/tests/QueryBuilderTest.php index ca08bf36a..6a3659cf4 100644 --- a/tests/QueryBuilderTest.php +++ b/tests/QueryBuilderTest.php @@ -419,6 +419,22 @@ public function testSubdocumentAggregate() $this->assertEquals(16.25, DB::collection('items')->avg('amount.hidden')); } + public function testSubdocumentArrayAggregate() + { + 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') From e615e53d6f329c795919c0da8da7df60997aa3c8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fiete=20B=C3=B6rner?= Date: Sun, 14 Aug 2016 00:24:24 +0200 Subject: [PATCH 20/88] change testSubdocumentArrayAggregate change test for different scenarios --- tests/QueryBuilderTest.php | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/tests/QueryBuilderTest.php b/tests/QueryBuilderTest.php index 6a3659cf4..9d45b17ba 100644 --- a/tests/QueryBuilderTest.php +++ b/tests/QueryBuilderTest.php @@ -422,17 +422,17 @@ public function testSubdocumentAggregate() public function testSubdocumentArrayAggregate() { DB::collection('items')->insert([ - ['name' => 'knife', 'amount' => [['hidden' => 10, 'found' => 3]]], - ['name' => 'fork', 'amount' => [['hidden' => 35, 'found' => 12]]], + ['name' => 'knife', 'amount' => [['hidden' => 10, 'found' => 3],['hidden' => 5, 'found' => 2]]], + ['name' => 'fork', 'amount' => [['hidden' => 35, 'found' => 12],['hidden' => 7, 'found' => 17],['hidden' => 1, 'found' => 19]]], ['name' => 'spoon', 'amount' => [['hidden' => 14, 'found' => 21]]], - ['name' => 'spoon', 'amount' => [['hidden' => 6, 'found' => 4]]], + ['name' => 'teaspoon', 'amount' => []], ]); - $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(72, DB::collection('items')->sum('amount.*.hidden')); + $this->assertEquals(6, DB::collection('items')->count('amount.*.hidden')); + $this->assertEquals(1, 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')); + $this->assertEquals(12, DB::collection('items')->avg('amount.*.hidden')); } public function testUpsert() From 408d267629b88560297c4633e417057c4d72be27 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fiete=20B=C3=B6rner?= Date: Thu, 1 Sep 2016 11:17:03 +0200 Subject: [PATCH 21/88] rebase to latest master and fix style ci issues --- src/Jenssegers/Mongodb/Query/Builder.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Jenssegers/Mongodb/Query/Builder.php b/src/Jenssegers/Mongodb/Query/Builder.php index 4aceeb421..4bfc69986 100644 --- a/src/Jenssegers/Mongodb/Query/Builder.php +++ b/src/Jenssegers/Mongodb/Query/Builder.php @@ -251,7 +251,7 @@ public function getFresh($columns = []) } // apply unwinds for subdocument array aggregation - foreach($unwinds as $unwind){ + foreach ($unwinds as $unwind) { $pipeline[] = ['$unwind' => '$' . $unwind]; } From c56241c53d83cdab46b900356fd4b54524075fa7 Mon Sep 17 00:00:00 2001 From: Pooya Parsa Date: Thu, 1 Sep 2016 02:28:01 -0700 Subject: [PATCH 22/88] Dot-Notation Fill Tests --- tests/ModelTest.php | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/tests/ModelTest.php b/tests/ModelTest.php index 3faa763f7..4058f1382 100644 --- a/tests/ModelTest.php +++ b/tests/ModelTest.php @@ -486,6 +486,13 @@ public function testDotNotation() $this->assertEquals('Paris', $user->getAttribute('address.city')); $this->assertEquals('Paris', $user['address.city']); $this->assertEquals('Paris', $user->{'address.city'}); + + // Fill + $user->fill([ + 'address.city' => 'Strasbourg', + ]); + + $this->assertEquals('Strasbourg', $user['address.city']); } public function testGetDirtyDates() From 5029a4f1f497f3eacd6ef48ed7497812a86cdb5d Mon Sep 17 00:00:00 2001 From: hooman naghiee Date: Fri, 2 Sep 2016 17:27:31 +0430 Subject: [PATCH 23/88] fix RelationsWithMongoIdTest --- tests/RelationsWithMongoIdTest.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tests/RelationsWithMongoIdTest.php b/tests/RelationsWithMongoIdTest.php index 517c3be99..30fdc0659 100644 --- a/tests/RelationsWithMongoIdTest.php +++ b/tests/RelationsWithMongoIdTest.php @@ -330,8 +330,8 @@ public function testBelongsToManyCustom() $this->assertTrue(array_key_exists('groups', $user->getAttributes())); // Assert they are attached - $this->assertTrue(in_array($group->_id, $user->groups)); - $this->assertTrue(in_array($user->_id, $group->users)); + $this->assertTrue(in_array($group->_id, $user->groups->pluck('_id')->toArray())); + $this->assertTrue(in_array($user->_id, $group->users->pluck('_id')->toArray())); $this->assertEquals($group->_id, $user->groups()->first()->_id); $this->assertEquals($user->_id, $group->users()->first()->_id); } From 54b9266ddcc30dd850c2c74df97aaa19ac4818bf Mon Sep 17 00:00:00 2001 From: hooman naghiee Date: Fri, 2 Sep 2016 17:35:39 +0430 Subject: [PATCH 24/88] "StyleCI" code style fix --- src/Jenssegers/Mongodb/Eloquent/Builder.php | 2 +- tests/RelationsWithMongoIdTest.php | 3 --- 2 files changed, 1 insertion(+), 4 deletions(-) diff --git a/src/Jenssegers/Mongodb/Eloquent/Builder.php b/src/Jenssegers/Mongodb/Eloquent/Builder.php index 73ac41646..be328516b 100644 --- a/src/Jenssegers/Mongodb/Eloquent/Builder.php +++ b/src/Jenssegers/Mongodb/Eloquent/Builder.php @@ -170,7 +170,7 @@ protected function addHasWhere(EloquentBuilder $hasQuery, Relation $relation, $o // Get the number of related objects for each possible parent. $relations = $query->pluck($relation->getHasCompareKey()); $relations = array_map(function ($id) { - return (string)$id; + return (string) $id; }, is_array($relations) ? $relations : $relations->toArray()); $relationCount = array_count_values($relations); diff --git a/tests/RelationsWithMongoIdTest.php b/tests/RelationsWithMongoIdTest.php index 30fdc0659..294d45ff4 100644 --- a/tests/RelationsWithMongoIdTest.php +++ b/tests/RelationsWithMongoIdTest.php @@ -2,7 +2,6 @@ class RelationsWithMongoIdTest extends TestCase { - public function setUp() { parent::setUp(); // TODO: Change the autogenerated stub @@ -420,13 +419,11 @@ public function testHasManyHas() $authors = User::whereHas('books', function ($query) { $query->where('rating', 5); - })->get(); $this->assertCount(1, $authors); $authors = User::whereHas('books', function ($query) { $query->where('rating', '<', 5); - })->get(); $this->assertCount(1, $authors); } From 2c70388ca056518801cc0042fae809758eb54355 Mon Sep 17 00:00:00 2001 From: hooman naghiee Date: Sat, 3 Sep 2016 11:24:07 +0430 Subject: [PATCH 25/88] remove unnecessary use_mongo_id that enable use_mongo_id for all tests --- tests/config/database.php | 1 - 1 file changed, 1 deletion(-) diff --git a/tests/config/database.php b/tests/config/database.php index c61c72bb2..e15a7a02d 100644 --- a/tests/config/database.php +++ b/tests/config/database.php @@ -9,7 +9,6 @@ 'driver' => 'mongodb', 'host' => '127.0.0.1', 'database' => 'unittest', - 'use_mongo_id' => true, ], 'mysql' => [ From 78707c0ebfd7478a47a084f39d01eb8418fbb11b Mon Sep 17 00:00:00 2001 From: hooman naghiee Date: Sat, 3 Sep 2016 11:24:35 +0430 Subject: [PATCH 26/88] remove missed patch file --- patch.txt | 46 ---------------------------------------------- 1 file changed, 46 deletions(-) delete mode 100644 patch.txt diff --git a/patch.txt b/patch.txt deleted file mode 100644 index e04703cc8..000000000 --- a/patch.txt +++ /dev/null @@ -1,46 +0,0 @@ -diff --git a/src/Jenssegers/Mongodb/Eloquent/Model.php b/src/Jenssegers/Mongodb/Eloquent/Model.php -index 3707c86cb7f732c97908d8ca3754118f4256e422..4a17b0f8c045b2d02f3f834ae0b207dccd2be311 100644 ---- a/src/Jenssegers/Mongodb/Eloquent/Model.php -+++ b/src/Jenssegers/Mongodb/Eloquent/Model.php -@@ -615,7 +615,7 @@ abstract class Model extends BaseModel - public function castAttribute($key, $value, $castType = 'get') - { - if (is_null($value)) { -- return null; -+ return; - } - - if (!$this->hasCast($key, null, $castType)) { -diff --git a/tests/RelationsWithMongoIdTest.php b/tests/RelationsWithMongoIdTest.php -index 8e78bf592b016b7a85609e699c6f0fa24c55dc0e..517c3be993b8eb68bae2349a061c6677be3cbfa7 100644 ---- a/tests/RelationsWithMongoIdTest.php -+++ b/tests/RelationsWithMongoIdTest.php -@@ -533,15 +533,15 @@ class RelationsWithMongoIdTest extends TestCase - $user = new User; - $user->setCasts([ - 'last_seen' => 'UTCDatetime', -- 'age'=>'int', -- 'name'=>'string', -- 'rate'=>'float', -- 'birthday'=>'timestamp', -- 'isActive'=>'bool', -- 'default'=>'default', -+ 'age' => 'int', -+ 'name' => 'string', -+ 'rate' => 'float', -+ 'birthday' => 'timestamp', -+ 'isActive' => 'bool', -+ 'default' => 'default', - ], 'set'); - $user->setCasts([ -- 'name'=>'string', -+ 'name' => 'string', - ]); - $carbon = Carbon\Carbon::now(); - $UTCDateTime = new \MongoDB\BSON\UTCDateTime($carbon->timestamp * 1000); -@@ -562,5 +562,4 @@ class RelationsWithMongoIdTest extends TestCase - $test = $user->castAttribute('default', 'test', 'set'); - $this->assertEquals('test', $test); - } -- - } From ab9807ef001477b2026b39faae3493d4a641514c Mon Sep 17 00:00:00 2001 From: pi0 Date: Sun, 4 Sep 2016 19:11:08 +0430 Subject: [PATCH 27/88] moloquent --- README.md | 955 +---------------------------------------------- composer.json | 9 +- phpunit.xml.dist | 2 +- 3 files changed, 22 insertions(+), 944 deletions(-) diff --git a/README.md b/README.md index 1a7f53c0a..1d122cd4e 100644 --- a/README.md +++ b/README.md @@ -1,948 +1,21 @@ -Laravel MongoDB -=============== +Moloquent (Laravel MongoDB) +============================= -[![Latest Stable Version](http://img.shields.io/github/release/jenssegers/laravel-mongodb.svg)](https://packagist.org/packages/jenssegers/mongodb) [![Total Downloads](http://img.shields.io/packagist/dm/jenssegers/mongodb.svg)](https://packagist.org/packages/jenssegers/mongodb) [![Build Status](http://img.shields.io/travis/jenssegers/laravel-mongodb.svg)](https://travis-ci.org/jenssegers/laravel-mongodb) [![Coverage Status](http://img.shields.io/coveralls/jenssegers/laravel-mongodb.svg)](https://coveralls.io/r/jenssegers/laravel-mongodb?branch=master) [![Donate](https://img.shields.io/badge/donate-paypal-blue.svg)](https://www.paypal.me/jenssegers) -An Eloquent model and Query builder with support for MongoDB, using the original Laravel API. *This library extends the original Laravel classes, so it uses exactly the same methods.* +[![Latest Stable Version](http://img.shields.io/github/release/moloquent/moloquent.svg)](https://packagist.org/packages/jenssegers/mongodb) +[![Total Downloads](http://img.shields.io/packagist/dm/moloquent/moloquent.svg)](https://packagist.org/packages/moloquent/moloquent) +[![Build Status](http://img.shields.io/travis/moloquent/moloquent.svg)](https://travis-ci.org/moloquent/moloquent) +[![Coverage Status](http://img.shields.io/coveralls/moloquent/moloquent.svg)](https://coveralls.io/r/moloquent/moloquent?branch=master) +[![Donate](https://img.shields.io/badge/donate-paypal-blue.svg)](https://www.paypal.me/jenssegers) -Table of contents ------------------ -* [Installation](#installation) -* [Upgrading](#upgrading) -* [Configuration](#configuration) -* [Eloquent](#eloquent) -* [Optional: Alias](#optional-alias) -* [Query Builder](#query-builder) -* [Schema](#schema) -* [Extensions](#extensions) -* [Troubleshooting](#troubleshooting) -* [Examples](#examples) +An Eloquent model and Query builder with support for MongoDB, using the original Laravel API.**This library extends the original Laravel classes, so it uses exactly the same methods.** -Installation ------------- +Getting Started +---------------- +Just go ahead to [Documentation](https://moloquent.github.io) to get started using this library. -Make sure you have the MongoDB PHP driver installed. You can find installation instructions at http://php.net/manual/en/mongodb.installation.php -**WARNING**: The old mongo PHP driver is not supported anymore in versions >= 3.0. - -Installation using composer: - -``` -composer require jenssegers/mongodb -``` - -### Laravel version Compatibility - - Laravel | Package -:---------|:---------- - 4.2.x | 2.0.x - 5.0.x | 2.1.x - 5.1.x | 2.2.x or 3.0.x - 5.2.x | 2.3.x or 3.0.x - 5.3.x | 3.1.x - -And add the service provider in `config/app.php`: - -```php -Jenssegers\Mongodb\MongodbServiceProvider::class, -``` - -For usage with [Lumen](http://lumen.laravel.com), add the service provider in `bootstrap/app.php`. In this file, you will also need to enable Eloquent. You must however ensure that your call to `$app->withEloquent();` is **below** where you have registered the `MongodbServiceProvider`: - -```php -$app->register('Jenssegers\Mongodb\MongodbServiceProvider'); - -$app->withEloquent(); -``` - -The service provider will register a mongodb database extension with the original database manager. There is no need to register additional facades or objects. When using mongodb connections, Laravel will automatically provide you with the corresponding mongodb objects. - -For usage outside Laravel, check out the [Capsule manager](https://github.com/illuminate/database/blob/master/README.md) and add: - -```php -$capsule->getDatabaseManager()->extend('mongodb', function($config) -{ - return new Jenssegers\Mongodb\Connection($config); -}); -``` - -Upgrading ---------- - -#### Upgrading from version 2 to 3 - -In this new major release which supports the new mongodb PHP extension, we also moved the location of the Model class and replaced the MySQL model class with a trait. - -Please change all `Jenssegers\Mongodb\Model` references to `Jenssegers\Mongodb\Eloquent\Model` either at the top of your model files, or your registered alias. - -```php -use Jenssegers\Mongodb\Eloquent\Model as Eloquent; - -class User extends Eloquent {} -``` - -If you are using hybrid relations, your MySQL classes should now extend the original Eloquent model class `Illuminate\Database\Eloquent\Model` instead of the removed `Jenssegers\Eloquent\Model`. Instead use the new `Jenssegers\Mongodb\Eloquent\HybridRelations` trait. This should make things more clear as there is only one single model class in this package. - -```php -use Jenssegers\Mongodb\Eloquent\HybridRelations; - -class User extends Eloquent { - - use HybridRelations; - - protected $connection = 'mysql'; - -} -``` - -Embedded relations now return an `Illuminate\Database\Eloquent\Collection` rather than a custom Collection class. If you were using one of the special methods that were available, convert them to Collection operations. - -```php -$books = $user->books()->sortBy('title'); -``` - -Configuration +Who are we ? ------------- - -Change your default database connection name in `config/database.php`: - -```php -'default' => env('DB_CONNECTION', 'mongodb'), -``` - -And add a new mongodb connection: - -```php -'mongodb' => [ - 'driver' => 'mongodb', - 'host' => env('DB_HOST', 'localhost'), - 'port' => env('DB_PORT', 27017), - 'database' => env('DB_DATABASE'), - 'username' => env('DB_USERNAME'), - 'password' => env('DB_PASSWORD'), - 'options' => [ - 'database' => 'admin' // sets the authentication database required by mongo 3 - ] -], -``` - -You can connect to multiple servers or replica sets with the following configuration: - -```php -'mongodb' => [ - 'driver' => 'mongodb', - 'host' => ['server1', 'server2'], - 'port' => env('DB_PORT', 27017), - 'database' => env('DB_DATABASE'), - 'username' => env('DB_USERNAME'), - 'password' => env('DB_PASSWORD'), - 'options' => ['replicaSet' => 'replicaSetName'] -], -``` - -Eloquent --------- - -This package includes a MongoDB enabled Eloquent class that you can use to define models for corresponding collections. - -```php -use Jenssegers\Mongodb\Eloquent\Model as Eloquent; - -class User extends Eloquent {} -``` - -Note that we did not tell Eloquent which collection to use for the `User` model. Just like the original Eloquent, the lower-case, plural name of the class will be used as the table name unless another name is explicitly specified. You may specify a custom collection (alias for table) by defining a `collection` property on your model: - -```php -use Jenssegers\Mongodb\Eloquent\Model as Eloquent; - -class User extends Eloquent { - - protected $collection = 'users_collection'; - -} -``` - -**NOTE:** Eloquent will also assume that each collection has a primary key column named id. You may define a `primaryKey` property to override this convention. Likewise, you may define a `connection` property to override the name of the database connection that should be used when utilizing the model. - -```php -use Jenssegers\Mongodb\Eloquent\Model as Eloquent; - -class MyModel extends Eloquent { - - protected $connection = 'mongodb'; - -} -``` - -Everything else (should) work just like the original Eloquent model. Read more about the Eloquent on http://laravel.com/docs/eloquent - -### Optional: Alias - -You may also register an alias for the MongoDB model by adding the following to the alias array in `config/app.php`: - -```php -'Moloquent' => 'Jenssegers\Mongodb\Eloquent\Model', -``` - -This will allow you to use the registered alias like: - -```php -class MyModel extends Moloquent {} -``` - -Query Builder -------------- - -The database driver plugs right into the original query builder. When using mongodb connections, you will be able to build fluent queries to perform database operations. For your convenience, there is a `collection` alias for `table` as well as some additional mongodb specific operators/operations. - -```php -$users = DB::collection('users')->get(); - -$user = DB::collection('users')->where('name', 'John')->first(); -``` - -If you did not change your default database connection, you will need to specify it when querying. - -```php -$user = DB::connection('mongodb')->collection('users')->get(); -``` - -Read more about the query builder on http://laravel.com/docs/queries - -Schema ------- - -The database driver also has (limited) schema builder support. You can easily manipulate collections and set indexes: - -```php -Schema::create('users', function($collection) -{ - $collection->index('name'); - - $collection->unique('email'); -}); -``` - -Supported operations are: - - - create and drop - - collection - - hasCollection - - index and dropIndex (compound indexes supported as well) - - unique - - background, sparse, expire (MongoDB specific) - -All other (unsupported) operations are implemented as dummy pass-through methods, because MongoDB does not use a predefined schema. Read more about the schema builder on http://laravel.com/docs/schema - -Extensions ----------- - -### Auth - -If you want to use Laravel's native Auth functionality, register this included service provider: - -```php -'Jenssegers\Mongodb\Auth\PasswordResetServiceProvider', -``` - -This service provider will slightly modify the internal DatabaseReminderRepository to add support for MongoDB based password reminders. If you don't use password reminders, you don't have to register this service provider and everything else should work just fine. - -### Queues - -If you want to use MongoDB as your database backend, change the the driver in `config/queue.php`: - -```php -'connections' => [ - 'database' => [ - 'driver' => 'mongodb', - 'table' => 'jobs', - 'queue' => 'default', - 'expire' => 60, - ], -``` - -If you want to use MongoDB to handle failed jobs, change the database in `config/queue.php`: - -```php -'failed' => [ - 'database' => 'mongodb', - 'table' => 'failed_jobs', - ], -``` - -And add the service provider in `config/app.php`: - -```php -Jenssegers\Mongodb\MongodbQueueServiceProvider::class, -``` - -### Sentry - -If you want to use this library with [Sentry](https://cartalyst.com/manual/sentry), then check out https://github.com/jenssegers/Laravel-MongoDB-Sentry - -### Sessions - -The MongoDB session driver is available in a separate package, check out https://github.com/jenssegers/Laravel-MongoDB-Session - -Examples --------- - -### Basic Usage - -**Retrieving All Models** - -```php -$users = User::all(); -``` - -**Retrieving A Record By Primary Key** - -```php -$user = User::find('517c43667db388101e00000f'); -``` - -**Wheres** - -```php -$users = User::where('votes', '>', 100)->take(10)->get(); -``` - -**Or Statements** - -```php -$users = User::where('votes', '>', 100)->orWhere('name', 'John')->get(); -``` - -**And Statements** - -```php -$users = User::where('votes', '>', 100)->where('name', '=', 'John')->get(); -``` - -**Using Where In With An Array** - -```php -$users = User::whereIn('age', [16, 18, 20])->get(); -``` - -When using `whereNotIn` objects will be returned if the field is non existent. Combine with `whereNotNull('age')` to leave out those documents. - -**Using Where Between** - -```php -$users = User::whereBetween('votes', [1, 100])->get(); -``` - -**Where null** - -```php -$users = User::whereNull('updated_at')->get(); -``` - -**Order By** - -```php -$users = User::orderBy('name', 'desc')->get(); -``` - -**Offset & Limit** - -```php -$users = User::skip(10)->take(5)->get(); -``` - -**Distinct** - -Distinct requires a field for which to return the distinct values. - -```php -$users = User::distinct()->get(['name']); -// or -$users = User::distinct('name')->get(); -``` - -Distinct can be combined with **where**: - -```php -$users = User::where('active', true)->distinct('name')->get(); -``` - -**Advanced Wheres** - -```php -$users = User::where('name', '=', 'John')->orWhere(function($query) - { - $query->where('votes', '>', 100) - ->where('title', '<>', 'Admin'); - }) - ->get(); -``` - -**Group By** - -Selected columns that are not grouped will be aggregated with the $last function. - -```php -$users = Users::groupBy('title')->get(['title', 'name']); -``` - -**Aggregation** - -*Aggregations are only available for MongoDB versions greater than 2.2.* - -```php -$total = Order::count(); -$price = Order::max('price'); -$price = Order::min('price'); -$price = Order::avg('price'); -$total = Order::sum('price'); -``` - -Aggregations can be combined with **where**: - -```php -$sold = Orders::where('sold', true)->sum('price'); -``` - -**Like** - -```php -$user = Comment::where('body', 'like', '%spam%')->get(); -``` - -**Incrementing or decrementing a value of a column** - -Perform increments or decrements (default 1) on specified attributes: - -```php -User::where('name', 'John Doe')->increment('age'); -User::where('name', 'Jaques')->decrement('weight', 50); -``` - -The number of updated objects is returned: - -```php -$count = User->increment('age'); -``` - -You may also specify additional columns to update: - -```php -User::where('age', '29')->increment('age', 1, ['group' => 'thirty something']); -User::where('bmi', 30)->decrement('bmi', 1, ['category' => 'overweight']); -``` - -**Soft deleting** - -When soft deleting a model, it is not actually removed from your database. Instead, a deleted_at timestamp is set on the record. To enable soft deletes for a model, apply the SoftDeletingTrait to the model: - -```php -use Jenssegers\Mongodb\Eloquent\SoftDeletes; - -class User extends Eloquent { - - use SoftDeletes; - - protected $dates = ['deleted_at']; - -} -``` - -For more information check http://laravel.com/docs/eloquent#soft-deleting - -### MongoDB specific operators - -**Exists** - -Matches documents that have the specified field. - -```php -User::where('age', 'exists', true)->get(); -``` - -**All** - -Matches arrays that contain all elements specified in the query. - -```php -User::where('roles', 'all', ['moderator', 'author'])->get(); -``` - -**Size** - -Selects documents if the array field is a specified size. - -```php -User::where('tags', 'size', 3)->get(); -``` - -**Regex** - -Selects documents where values match a specified regular expression. - -```php -User::where('name', 'regex', new MongoRegex("/.*doe/i"))->get(); -``` - -**NOTE:** you can also use the Laravel regexp operations. These are a bit more flexible and will automatically convert your regular expression string to a MongoRegex object. - -```php -User::where('name', 'regexp', '/.*doe/i'))->get(); -``` - -And the inverse: - -```php -User::where('name', 'not regexp', '/.*doe/i'))->get(); -``` - -**Type** - -Selects documents if a field is of the specified type. For more information check: http://docs.mongodb.org/manual/reference/operator/query/type/#op._S_type - -```php -User::where('age', 'type', 2)->get(); -``` - -**Mod** - -Performs a modulo operation on the value of a field and selects documents with a specified result. - -```php -User::where('age', 'mod', [10, 0])->get(); -``` - -**Where** - -Matches documents that satisfy a JavaScript expression. For more information check http://docs.mongodb.org/manual/reference/operator/query/where/#op._S_where - -### Inserts, updates and deletes - -Inserting, updating and deleting records works just like the original Eloquent. - -**Saving a new model** - -```php -$user = new User; -$user->name = 'John'; -$user->save(); -``` - -You may also use the create method to save a new model in a single line: - -```php -User::create(['name' => 'John']); -``` - -**Updating a model** - -To update a model, you may retrieve it, change an attribute, and use the save method. - -```php -$user = User::first(); -$user->email = 'john@foo.com'; -$user->save(); -``` - -*There is also support for upsert operations, check https://github.com/jenssegers/laravel-mongodb#mongodb-specific-operations* - -**Deleting a model** - -To delete a model, simply call the delete method on the instance: - -```php -$user = User::first(); -$user->delete(); -``` - -Or deleting a model by its key: - -```php -User::destroy('517c43667db388101e00000f'); -``` - -For more information about model manipulation, check http://laravel.com/docs/eloquent#insert-update-delete - -### Dates - -Eloquent allows you to work with Carbon/DateTime objects instead of MongoDate objects. Internally, these dates will be converted to MongoDate objects when saved to the database. If you wish to use this functionality on non-default date fields you will need to manually specify them as described here: http://laravel.com/docs/eloquent#date-mutators - -Example: - -```php -use Jenssegers\Mongodb\Eloquent\Model as Eloquent; - -class User extends Eloquent { - - protected $dates = ['birthday']; - -} -``` - -Which allows you to execute queries like: - -```php -$users = User::where('birthday', '>', new DateTime('-18 years'))->get(); -``` - -### Relations - -Supported relations are: - - - hasOne - - hasMany - - belongsTo - - belongsToMany - - embedsOne - - embedsMany - -Example: - -```php -use Jenssegers\Mongodb\Eloquent\Model as Eloquent; - -class User extends Eloquent { - - public function items() - { - return $this->hasMany('Item'); - } - -} -``` - -And the inverse relation: - -```php -use Jenssegers\Mongodb\Eloquent\Model as Eloquent; - -class Item extends Eloquent { - - public function user() - { - return $this->belongsTo('User'); - } - -} -``` - -The belongsToMany relation will not use a pivot "table", but will push id's to a __related_ids__ attribute instead. This makes the second parameter for the belongsToMany method useless. If you want to define custom keys for your relation, set it to `null`: - -```php -use Jenssegers\Mongodb\Eloquent\Model as Eloquent; - -class User extends Eloquent { - - public function groups() - { - return $this->belongsToMany('Group', null, 'user_ids', 'group_ids'); - } - -} -``` - - -Other relations are not yet supported, but may be added in the future. Read more about these relations on http://laravel.com/docs/eloquent#relationships - -### EmbedsMany Relations - -If you want to embed models, rather than referencing them, you can use the `embedsMany` relation. This relation is similar to the `hasMany` relation, but embeds the models inside the parent object. - -**REMEMBER**: these relations return Eloquent collections, they don't return query builder objects! - -```php -use Jenssegers\Mongodb\Eloquent\Model as Eloquent; - -class User extends Eloquent { - - public function books() - { - return $this->embedsMany('Book'); - } - -} -``` - -You access the embedded models through the dynamic property: - -```php -$books = User::first()->books; -``` - -The inverse relation is auto*magically* available, you don't need to define this reverse relation. - -```php -$user = $book->user; -``` - -Inserting and updating embedded models works similar to the `hasMany` relation: - -```php -$book = new Book(['title' => 'A Game of Thrones']); - -$user = User::first(); - -$book = $user->books()->save($book); -// or -$book = $user->books()->create(['title' => 'A Game of Thrones']) -``` - -You can update embedded models using their `save` method (available since release 2.0.0): - -```php -$book = $user->books()->first(); - -$book->title = 'A Game of Thrones'; - -$book->save(); -``` - -You can remove an embedded model by using the `destroy` method on the relation, or the `delete` method on the model (available since release 2.0.0): - -```php -$book = $user->books()->first(); - -$book->delete(); -// or -$user->books()->destroy($book); -``` - -If you want to add or remove an embedded model, without touching the database, you can use the `associate` and `dissociate` methods. To eventually write the changes to the database, save the parent object: - -```php -$user->books()->associate($book); - -$user->save(); -``` - -Like other relations, embedsMany assumes the local key of the relationship based on the model name. You can override the default local key by passing a second argument to the embedsMany method: - -```php -return $this->embedsMany('Book', 'local_key'); -``` - -Embedded relations will return a Collection of embedded items instead of a query builder. Check out the available operations here: https://laravel.com/docs/master/collections - -### EmbedsOne Relations - -The embedsOne relation is similar to the EmbedsMany relation, but only embeds a single model. - -```php -use Jenssegers\Mongodb\Eloquent\Model as Eloquent; - -class Book extends Eloquent { - - public function author() - { - return $this->embedsOne('Author'); - } - -} -``` - -You access the embedded models through the dynamic property: - -```php -$author = Book::first()->author; -``` - -Inserting and updating embedded models works similar to the `hasOne` relation: - -```php -$author = new Author(['name' => 'John Doe']); - -$book = Books::first(); - -$author = $book->author()->save($author); -// or -$author = $book->author()->create(['name' => 'John Doe']); -``` - -You can update the embedded model using the `save` method (available since release 2.0.0): - -```php -$author = $book->author; - -$author->name = 'Jane Doe'; -$author->save(); -``` - -You can replace the embedded model with a new model like this: - -```php -$newAuthor = new Author(['name' => 'Jane Doe']); -$book->author()->save($newAuthor); -``` - -### MySQL Relations - -If you're using a hybrid MongoDB and SQL setup, you're in luck! The model will automatically return a MongoDB- or SQL-relation based on the type of the related model. Of course, if you want this functionality to work both ways, your SQL-models will need use the `Jenssegers\Mongodb\Eloquent\HybridRelations` trait. Note that this functionality only works for hasOne, hasMany and belongsTo relations. - -Example SQL-based User model: - -```php -use Jenssegers\Mongodb\Eloquent\HybridRelations; - -class User extends Eloquent { - - use HybridRelations; - - protected $connection = 'mysql'; - - public function messages() - { - return $this->hasMany('Message'); - } - -} -``` - -And the Mongodb-based Message model: - -```php -use Jenssegers\Mongodb\Eloquent\Model as Eloquent; - -class Message extends Eloquent { - - protected $connection = 'mongodb'; - - public function user() - { - return $this->belongsTo('User'); - } - -} -``` - -### Raw Expressions - -These expressions will be injected directly into the query. - -```php -User::whereRaw(['age' => array('$gt' => 30, '$lt' => 40)])->get(); -``` - -You can also perform raw expressions on the internal MongoCollection object. If this is executed on the model class, it will return a collection of models. If this is executed on the query builder, it will return the original response. - -```php -// Returns a collection of User models. -$models = User::raw(function($collection) -{ - return $collection->find(); -}); - -// Returns the original MongoCursor. -$cursor = DB::collection('users')->raw(function($collection) -{ - return $collection->find(); -}); -``` - -Optional: if you don't pass a closure to the raw method, the internal MongoCollection object will be accessible: - -```php -$model = User::raw()->findOne(['age' => array('$lt' => 18])); -``` - -The internal MongoClient and MongoDB objects can be accessed like this: - -```php -$client = DB::getMongoClient(); -$db = DB::getMongoDB(); -``` - -### MongoDB specific operations - -**Cursor timeout** - -To prevent MongoCursorTimeout exceptions, you can manually set a timeout value that will be applied to the cursor: - -```php -DB::collection('users')->timeout(-1)->get(); -``` - -**Upsert** - -Update or insert a document. Additional options for the update method are passed directly to the native update method. - -```php -DB::collection('users')->where('name', 'John') - ->update($data, ['upsert' => true]); -``` - -**Projections** - -You can apply projections to your queries using the `project` method. - -```php -DB::collection('items')->project(['tags' => array('$slice' => 1]))->get(); -``` - -**Projections with Pagination** - -```php -$limit = 25; -$projections = ['id', 'name']; -DB::collection('items')->paginate($limit, $projections); -``` - - -**Push** - -Add an items to an array. - -```php -DB::collection('users')->where('name', 'John')->push('items', 'boots'); -DB::collection('users')->where('name', 'John')->push('messages', ['from' => 'Jane Doe', 'message' => 'Hi John']); -``` - -If you don't want duplicate items, set the third parameter to `true`: - -```php -DB::collection('users')->where('name', 'John')->push('items', 'boots', true); -``` - -**Pull** - -Remove an item from an array. - -```php -DB::collection('users')->where('name', 'John')->pull('items', 'boots'); -DB::collection('users')->where('name', 'John')->pull('messages', ['from' => 'Jane Doe', 'message' => 'Hi John']); -``` - -**Unset** - -Remove one or more fields from a document. - -```php -DB::collection('users')->where('name', 'John')->unset('note'); -``` - -You can also perform an unset on a model. - -```php -$user = User::where('name', 'John')->first(); -$user->unset('note'); -``` - -### Query Caching - -You may easily cache the results of a query using the remember method: - -```php -$users = User::remember(10)->get(); -``` - -*From: http://laravel.com/docs/queries#caching-queries* - -### Query Logging - -By default, Laravel keeps a log in memory of all queries that have been run for the current request. However, in some cases, such as when inserting a large number of rows, this can cause the application to use excess memory. To disable the log, you may use the `disableQueryLog` method: - -```php -DB::connection()->disableQueryLog(); -``` - -*From: http://laravel.com/docs/database#query-logging* +The base repo WAS and IS being developed and maintained by [Jenssegers](https://github.com/jenssegers/laravel-mongodb). +Our goal is to provide higher quality support/bugfixes with fresh and additional features. diff --git a/composer.json b/composer.json index c98a67dff..d44f1aa3a 100644 --- a/composer.json +++ b/composer.json @@ -1,9 +1,13 @@ { - "name": "jenssegers/mongodb", + "name": "moloquent", "description": "A MongoDB based Eloquent model and Query builder for Laravel (Moloquent)", "keywords": ["laravel","eloquent","mongodb","mongo","database","model","moloquent"], - "homepage": "https://github.com/jenssegers/laravel-mongodb", + "homepage": "https://github.com/moloquent/moloquent", "authors": [ + { + "name": "Moloquent", + "homepage": "https://moloquent.github.io" + }, { "name": "Jens Segers", "homepage": "https://jenssegers.com" @@ -26,6 +30,7 @@ }, "autoload": { "psr-0": { + "Moloquent\\Moloquent": "src/", "Jenssegers\\Mongodb": "src/", "Jenssegers\\Eloquent": "src/" } diff --git a/phpunit.xml.dist b/phpunit.xml.dist index 796bd5b38..bd9d7f5c4 100644 --- a/phpunit.xml.dist +++ b/phpunit.xml.dist @@ -7,7 +7,7 @@ convertNoticesToExceptions="true" convertWarningsToExceptions="true" processIsolation="false" - stopOnFailure="true" + stopOnFailure="false" syntaxCheck="false" verbose="true" > From da25723108cb759eaf85f01e0149e9a96d61d742 Mon Sep 17 00:00:00 2001 From: pi0 Date: Sun, 4 Sep 2016 19:14:08 +0430 Subject: [PATCH 28/88] change package namespace --- composer.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/composer.json b/composer.json index d44f1aa3a..6d2013c11 100644 --- a/composer.json +++ b/composer.json @@ -1,5 +1,5 @@ { - "name": "moloquent", + "name": "moloquent/moloquent", "description": "A MongoDB based Eloquent model and Query builder for Laravel (Moloquent)", "keywords": ["laravel","eloquent","mongodb","mongo","database","model","moloquent"], "homepage": "https://github.com/moloquent/moloquent", From f1528df1e5a65329167408e0b562c51cfbb15ffe Mon Sep 17 00:00:00 2001 From: pi0 Date: Sun, 4 Sep 2016 19:34:00 +0430 Subject: [PATCH 29/88] badges --- README.md | 4 +-- composer.json | 98 ++++++++++++++++++++++++++++----------------------- 2 files changed, 55 insertions(+), 47 deletions(-) diff --git a/README.md b/README.md index 1d122cd4e..0005d18e7 100644 --- a/README.md +++ b/README.md @@ -2,8 +2,8 @@ Moloquent (Laravel MongoDB) ============================= -[![Latest Stable Version](http://img.shields.io/github/release/moloquent/moloquent.svg)](https://packagist.org/packages/jenssegers/mongodb) -[![Total Downloads](http://img.shields.io/packagist/dm/moloquent/moloquent.svg)](https://packagist.org/packages/moloquent/moloquent) +[![Latest Version](http://img.shields.io/packagist/v/moloquent/moloquent.svg)](https://packagist.org/packages/moloquent/moloquent) +[![Downloads](http://img.shields.io/packagist/dt/moloquent/moloquent.svg)](https://packagist.org/packages/moloquent/moloquent) [![Build Status](http://img.shields.io/travis/moloquent/moloquent.svg)](https://travis-ci.org/moloquent/moloquent) [![Coverage Status](http://img.shields.io/coveralls/moloquent/moloquent.svg)](https://coveralls.io/r/moloquent/moloquent?branch=master) [![Donate](https://img.shields.io/badge/donate-paypal-blue.svg)](https://www.paypal.me/jenssegers) diff --git a/composer.json b/composer.json index 6d2013c11..65bbbaeb8 100644 --- a/composer.json +++ b/composer.json @@ -1,49 +1,57 @@ { - "name": "moloquent/moloquent", - "description": "A MongoDB based Eloquent model and Query builder for Laravel (Moloquent)", - "keywords": ["laravel","eloquent","mongodb","mongo","database","model","moloquent"], - "homepage": "https://github.com/moloquent/moloquent", - "authors": [ - { - "name": "Moloquent", - "homepage": "https://moloquent.github.io" - }, - { - "name": "Jens Segers", - "homepage": "https://jenssegers.com" - } - ], - "license" : "MIT", - "require": { - "illuminate/support": "^5.1", - "illuminate/container": "^5.1", - "illuminate/database": "^5.1", - "illuminate/events": "^5.1", - "mongodb/mongodb": "^1.0.0" - + "name": "moloquent/moloquent", + "version": "3.1.0", + "description": "A MongoDB based Eloquent model and Query builder for Laravel (Moloquent)", + "keywords": [ + "laravel", + "eloquent", + "mongodb", + "mongo", + "database", + "model", + "moloquent" + ], + "homepage": "https://github.com/moloquent/moloquent", + "authors": [ + { + "name": "Moloquent", + "homepage": "https://moloquent.github.io" }, - "require-dev": { - "phpunit/phpunit": "^4.0|^5.0", - "orchestra/testbench": "^3.1", - "mockery/mockery": "^0.9", - "satooshi/php-coveralls": "^0.6" - }, - "autoload": { - "psr-0": { - "Moloquent\\Moloquent": "src/", - "Jenssegers\\Mongodb": "src/", - "Jenssegers\\Eloquent": "src/" - } - }, - "autoload-dev": { - "classmap": [ - "tests/TestCase.php", - "tests/models", - "tests/seeds" - ] - }, - "suggest": { - "jenssegers/mongodb-session": "Add MongoDB session support to Laravel-MongoDB", - "jenssegers/mongodb-sentry": "Add Sentry support to Laravel-MongoDB" + { + "name": "Jens Segers", + "homepage": "https://jenssegers.com" + } + ], + "license": "MIT", + "require": { + "illuminate/support": "^5.1", + "illuminate/container": "^5.1", + "illuminate/database": "^5.1", + "illuminate/events": "^5.1", + "mongodb/mongodb": "^1.0.0" + }, + "require-dev": { + "phpunit/phpunit": "^4.0|^5.0", + "orchestra/testbench": "^3.1", + "mockery/mockery": "^0.9", + "satooshi/php-coveralls": "^0.6" + }, + "autoload": { + "psr-0": { + "Moloquent\\Moloquent": "src/", + "Jenssegers\\Mongodb": "src/", + "Jenssegers\\Eloquent": "src/" } + }, + "autoload-dev": { + "classmap": [ + "tests/TestCase.php", + "tests/models", + "tests/seeds" + ] + }, + "suggest": { + "jenssegers/mongodb-session": "Add MongoDB session support to Laravel-MongoDB", + "jenssegers/mongodb-sentry": "Add Sentry support to Laravel-MongoDB" + } } From 28ecb85553320e4ad69eaf2baf3b9a7d7c2e16fa Mon Sep 17 00:00:00 2001 From: pi0 Date: Tue, 6 Sep 2016 23:35:39 +0430 Subject: [PATCH 30/88] Code Coverage --- .gitignore | 1 + .travis.yml | 2 +- phpunit.xml.dist | 7 +++++++ .../Queue/Failed/MongoFailedJobProvider.php | 14 +++++++------- 4 files changed, 16 insertions(+), 8 deletions(-) diff --git a/.gitignore b/.gitignore index 1fe4e30f6..027823e15 100644 --- a/.gitignore +++ b/.gitignore @@ -7,3 +7,4 @@ composer.lock *.sublime-workspace *.project .idea/ +build/ \ No newline at end of file diff --git a/.travis.yml b/.travis.yml index 357d4036a..0cf18d710 100644 --- a/.travis.yml +++ b/.travis.yml @@ -31,4 +31,4 @@ script: - vendor/bin/phpunit --coverage-clover build/logs/clover.xml after_success: - - sh -c 'php vendor/bin/coveralls -v' + - coveralls diff --git a/phpunit.xml.dist b/phpunit.xml.dist index a25b6ce31..cf7703c88 100644 --- a/phpunit.xml.dist +++ b/phpunit.xml.dist @@ -46,4 +46,11 @@ tests/ValidationTest.php + + + + src + + + diff --git a/src/Jenssegers/Mongodb/Queue/Failed/MongoFailedJobProvider.php b/src/Jenssegers/Mongodb/Queue/Failed/MongoFailedJobProvider.php index 4234f885d..e00757ac5 100644 --- a/src/Jenssegers/Mongodb/Queue/Failed/MongoFailedJobProvider.php +++ b/src/Jenssegers/Mongodb/Queue/Failed/MongoFailedJobProvider.php @@ -8,17 +8,17 @@ class MongoFailedJobProvider extends DatabaseFailedJobProvider /** * Log a failed job into storage. * - * @param string $connection - * @param string $queue - * @param string $payload - * - * @return void + * @param string $connection + * @param string $queue + * @param string $payload + * @param \Exception $exception + * @return int|null */ - public function log($connection, $queue, $payload) + public function log($connection, $queue, $payload, $exception) { $failed_at = Carbon::now()->getTimestamp(); - $this->getTable()->insert(compact('connection', 'queue', 'payload', 'failed_at')); + $this->getTable()->insert(compact('connection', 'queue', 'payload', 'failed_at','exception')); } /** From 5a4c46980593ab68e95d60792874ecc0e4c94f6e Mon Sep 17 00:00:00 2001 From: pi0 Date: Tue, 6 Sep 2016 23:49:41 +0430 Subject: [PATCH 31/88] coveralls --- .travis.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index 0cf18d710..3e93fe2ab 100644 --- a/.travis.yml +++ b/.travis.yml @@ -31,4 +31,4 @@ script: - vendor/bin/phpunit --coverage-clover build/logs/clover.xml after_success: - - coveralls + - sh -c 'php vendor/bin/coveralls -v' From 9909714322a2c2adb8210815c5a8606eb044dfda Mon Sep 17 00:00:00 2001 From: pi0 Date: Thu, 8 Sep 2016 00:54:37 +0430 Subject: [PATCH 32/88] psr-4 namespace --- composer.json | 12 ++------ moloquent.iml | 11 ++++++++ .../Auth/DatabaseTokenRepository.php | 2 +- .../Auth/PasswordBrokerManager.php | 2 +- .../Auth/PasswordResetServiceProvider.php | 2 +- .../Mongodb => Moloquent}/Collection.php | 2 +- .../Mongodb => Moloquent}/Connection.php | 5 ++-- .../Eloquent/Builder.php | 2 +- .../Eloquent/HybridRelations.php | 28 +++++++++---------- .../Mongodb => Moloquent}/Eloquent/Model.php | 18 ++++++------ .../Eloquent/SoftDeletes.php | 2 +- .../MongodbQueueServiceProvider.php | 4 +-- .../MongodbServiceProvider.php | 6 ++-- .../Mongodb => Moloquent}/Query/Builder.php | 4 +-- .../Mongodb => Moloquent}/Query/Grammar.php | 2 +- .../Mongodb => Moloquent}/Query/Processor.php | 2 +- .../Queue/Failed/MongoFailedJobProvider.php | 2 +- .../Queue/MongoConnector.php | 2 +- .../Queue/MongoQueue.php | 2 +- .../Relations/BelongsTo.php | 2 +- .../Relations/BelongsToMany.php | 2 +- .../Relations/EmbedsMany.php | 2 +- .../Relations/EmbedsOne.php | 2 +- .../Relations/EmbedsOneOrMany.php | 4 +-- .../Relations/HasMany.php | 2 +- .../Relations/HasOne.php | 2 +- .../Relations/HasOneOrManyTrait.php | 7 ++--- .../Relations/MorphMany.php | 3 +- .../Relations/MorphOne.php | 3 +- .../Relations/MorphTo.php | 2 +- .../Schema/Blueprint.php | 2 +- .../Mongodb => Moloquent}/Schema/Builder.php | 4 +-- tests/CollectionTest.php | 4 +-- tests/ConnectionTest.php | 10 +++---- tests/ModelTest.php | 16 +++++------ tests/QueryBuilderTest.php | 6 ++-- tests/SchemaTest.php | 6 ++-- tests/TestCase.php | 4 +-- tests/models/Address.php | 2 +- tests/models/Book.php | 3 +- tests/models/Client.php | 2 +- tests/models/Group.php | 2 +- tests/models/Item.php | 2 +- tests/models/MysqlBook.php | 3 +- tests/models/MysqlRole.php | 3 +- tests/models/MysqlUser.php | 3 +- tests/models/Photo.php | 2 +- tests/models/Role.php | 2 +- tests/models/Soft.php | 4 +-- tests/models/User.php | 2 +- 50 files changed, 115 insertions(+), 108 deletions(-) create mode 100644 moloquent.iml rename src/{Jenssegers/Mongodb => Moloquent}/Auth/DatabaseTokenRepository.php (97%) rename src/{Jenssegers/Mongodb => Moloquent}/Auth/PasswordBrokerManager.php (93%) rename src/{Jenssegers/Mongodb => Moloquent}/Auth/PasswordResetServiceProvider.php (97%) rename src/{Jenssegers/Mongodb => Moloquent}/Collection.php (98%) rename src/{Jenssegers/Mongodb => Moloquent}/Connection.php (98%) rename src/{Jenssegers/Mongodb => Moloquent}/Eloquent/Builder.php (99%) rename src/{Jenssegers/Mongodb => Moloquent}/Eloquent/HybridRelations.php (91%) rename src/{Jenssegers/Mongodb => Moloquent}/Eloquent/Model.php (97%) rename src/{Jenssegers/Mongodb => Moloquent}/Eloquent/SoftDeletes.php (86%) rename src/{Jenssegers/Mongodb => Moloquent}/MongodbQueueServiceProvider.php (87%) rename src/{Jenssegers/Mongodb => Moloquent}/MongodbServiceProvider.php (87%) rename src/{Jenssegers/Mongodb => Moloquent}/Query/Builder.php (99%) rename src/{Jenssegers/Mongodb => Moloquent}/Query/Grammar.php (71%) rename src/{Jenssegers/Mongodb => Moloquent}/Query/Processor.php (72%) rename src/{Jenssegers/Mongodb => Moloquent}/Queue/Failed/MongoFailedJobProvider.php (96%) rename src/{Jenssegers/Mongodb => Moloquent}/Queue/MongoConnector.php (96%) rename src/{Jenssegers/Mongodb => Moloquent}/Queue/MongoQueue.php (98%) rename src/{Jenssegers/Mongodb => Moloquent}/Relations/BelongsTo.php (98%) rename src/{Jenssegers/Mongodb => Moloquent}/Relations/BelongsToMany.php (99%) rename src/{Jenssegers/Mongodb => Moloquent}/Relations/EmbedsMany.php (99%) rename src/{Jenssegers/Mongodb => Moloquent}/Relations/EmbedsOne.php (98%) rename src/{Jenssegers/Mongodb => Moloquent}/Relations/EmbedsOneOrMany.php (98%) rename src/{Jenssegers/Mongodb => Moloquent}/Relations/HasMany.php (96%) rename src/{Jenssegers/Mongodb => Moloquent}/Relations/HasOne.php (96%) rename src/{Jenssegers/Mongodb => Moloquent}/Relations/HasOneOrManyTrait.php (93%) rename src/{Jenssegers/Mongodb => Moloquent}/Relations/MorphMany.php (76%) rename src/{Jenssegers/Mongodb => Moloquent}/Relations/MorphOne.php (76%) rename src/{Jenssegers/Mongodb => Moloquent}/Relations/MorphTo.php (97%) rename src/{Jenssegers/Mongodb => Moloquent}/Schema/Blueprint.php (99%) rename src/{Jenssegers/Mongodb => Moloquent}/Schema/Builder.php (97%) diff --git a/composer.json b/composer.json index 65bbbaeb8..da7e8d27f 100644 --- a/composer.json +++ b/composer.json @@ -1,6 +1,6 @@ { "name": "moloquent/moloquent", - "version": "3.1.0", + "version": "5.3.0", "description": "A MongoDB based Eloquent model and Query builder for Laravel (Moloquent)", "keywords": [ "laravel", @@ -37,10 +37,8 @@ "satooshi/php-coveralls": "^0.6" }, "autoload": { - "psr-0": { - "Moloquent\\Moloquent": "src/", - "Jenssegers\\Mongodb": "src/", - "Jenssegers\\Eloquent": "src/" + "psr-4" :{ + "Moloquent\\": "src/" } }, "autoload-dev": { @@ -49,9 +47,5 @@ "tests/models", "tests/seeds" ] - }, - "suggest": { - "jenssegers/mongodb-session": "Add MongoDB session support to Laravel-MongoDB", - "jenssegers/mongodb-sentry": "Add Sentry support to Laravel-MongoDB" } } diff --git a/moloquent.iml b/moloquent.iml new file mode 100644 index 000000000..13b229f58 --- /dev/null +++ b/moloquent.iml @@ -0,0 +1,11 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/src/Jenssegers/Mongodb/Auth/DatabaseTokenRepository.php b/src/Moloquent/Auth/DatabaseTokenRepository.php similarity index 97% rename from src/Jenssegers/Mongodb/Auth/DatabaseTokenRepository.php rename to src/Moloquent/Auth/DatabaseTokenRepository.php index 43edb9fd1..d5903e293 100644 --- a/src/Jenssegers/Mongodb/Auth/DatabaseTokenRepository.php +++ b/src/Moloquent/Auth/DatabaseTokenRepository.php @@ -1,4 +1,4 @@ -assertInstanceOf('Jenssegers\Mongodb\Connection', $connection); + $this->assertInstanceOf('Moloquent\Connection', $connection); } public function testReconnect() @@ -32,13 +32,13 @@ public function testDb() public function testCollection() { $collection = DB::connection('mongodb')->getCollection('unittest'); - $this->assertInstanceOf('Jenssegers\Mongodb\Collection', $collection); + $this->assertInstanceOf('Moloquent\Collection', $collection); $collection = DB::connection('mongodb')->collection('unittests'); - $this->assertInstanceOf('Jenssegers\Mongodb\Query\Builder', $collection); + $this->assertInstanceOf('Moloquent\Query\Builder', $collection); $collection = DB::connection('mongodb')->table('unittests'); - $this->assertInstanceOf('Jenssegers\Mongodb\Query\Builder', $collection); + $this->assertInstanceOf('Moloquent\Query\Builder', $collection); } // public function testDynamic() @@ -87,7 +87,7 @@ public function testQueryLog() public function testSchemaBuilder() { $schema = DB::connection('mongodb')->getSchemaBuilder(); - $this->assertInstanceOf('Jenssegers\Mongodb\Schema\Builder', $schema); + $this->assertInstanceOf('Moloquent\Schema\Builder', $schema); } public function testDriverName() diff --git a/tests/ModelTest.php b/tests/ModelTest.php index 4058f1382..e9f6bf306 100644 --- a/tests/ModelTest.php +++ b/tests/ModelTest.php @@ -13,8 +13,8 @@ public function tearDown() public function testNewModel() { $user = new User; - $this->assertInstanceOf('Jenssegers\Mongodb\Eloquent\Model', $user); - $this->assertInstanceOf('Jenssegers\Mongodb\Connection', $user->getConnection()); + $this->assertInstanceOf('Moloquent\Eloquent\Model', $user); + $this->assertInstanceOf('Moloquent\Connection', $user->getConnection()); $this->assertEquals(false, $user->exists); $this->assertEquals('users', $user->getTable()); $this->assertEquals('_id', $user->getKeyName()); @@ -170,7 +170,7 @@ public function testFind() $check = User::find($user->_id); - $this->assertInstanceOf('Jenssegers\Mongodb\Eloquent\Model', $check); + $this->assertInstanceOf('Moloquent\Eloquent\Model', $check); $this->assertEquals(true, $check->exists); $this->assertEquals($user->_id, $check->_id); @@ -188,7 +188,7 @@ public function testGet() $users = User::get(); $this->assertEquals(2, count($users)); $this->assertInstanceOf('Illuminate\Database\Eloquent\Collection', $users); - $this->assertInstanceOf('Jenssegers\Mongodb\Eloquent\Model', $users[0]); + $this->assertInstanceOf('Moloquent\Eloquent\Model', $users[0]); } public function testFirst() @@ -199,7 +199,7 @@ public function testFirst() ]); $user = User::first(); - $this->assertInstanceOf('Jenssegers\Mongodb\Eloquent\Model', $user); + $this->assertInstanceOf('Moloquent\Eloquent\Model', $user); $this->assertEquals('John Doe', $user->name); } @@ -226,7 +226,7 @@ public function testCreate() { $user = User::create(['name' => 'Jane Poe']); - $this->assertInstanceOf('Jenssegers\Mongodb\Eloquent\Model', $user); + $this->assertInstanceOf('Moloquent\Eloquent\Model', $user); $this->assertEquals(true, $user->exists); $this->assertEquals('Jane Poe', $user->name); @@ -454,13 +454,13 @@ public function testRaw() return $collection->find(['age' => 35]); }); $this->assertInstanceOf('Illuminate\Database\Eloquent\Collection', $users); - $this->assertInstanceOf('Jenssegers\Mongodb\Eloquent\Model', $users[0]); + $this->assertInstanceOf('Moloquent\Eloquent\Model', $users[0]); $user = User::raw(function ($collection) { return $collection->findOne(['age' => 35]); }); - $this->assertInstanceOf('Jenssegers\Mongodb\Eloquent\Model', $user); + $this->assertInstanceOf('Moloquent\Eloquent\Model', $user); $count = User::raw(function ($collection) { return $collection->count(); diff --git a/tests/QueryBuilderTest.php b/tests/QueryBuilderTest.php index 9d45b17ba..81d9ca93b 100644 --- a/tests/QueryBuilderTest.php +++ b/tests/QueryBuilderTest.php @@ -13,7 +13,7 @@ public function tearDown() public function testCollection() { - $this->assertInstanceOf('Jenssegers\Mongodb\Query\Builder', DB::collection('users')); + $this->assertInstanceOf('Moloquent\Query\Builder', DB::collection('users')); } public function testGet() @@ -190,10 +190,10 @@ public function testRaw() $this->assertEquals(1, count($cursor->toArray())); $collection = DB::collection('users')->raw(); - $this->assertInstanceOf('Jenssegers\Mongodb\Collection', $collection); + $this->assertInstanceOf('Moloquent\Collection', $collection); $collection = User::raw(); - $this->assertInstanceOf('Jenssegers\Mongodb\Collection', $collection); + $this->assertInstanceOf('Moloquent\Collection', $collection); $results = DB::collection('users')->whereRaw(['age' => 20])->get(); $this->assertEquals(1, count($results)); diff --git a/tests/SchemaTest.php b/tests/SchemaTest.php index 6f7b0f0e2..df51af09f 100644 --- a/tests/SchemaTest.php +++ b/tests/SchemaTest.php @@ -19,7 +19,7 @@ public function testCreateWithCallback() $instance = $this; Schema::create('newcollection', function ($collection) use ($instance) { - $instance->assertInstanceOf('Jenssegers\Mongodb\Schema\Blueprint', $collection); + $instance->assertInstanceOf('Moloquent\Schema\Blueprint', $collection); }); $this->assertTrue(Schema::hasCollection('newcollection')); @@ -37,11 +37,11 @@ public function testBluePrint() $instance = $this; Schema::collection('newcollection', function ($collection) use ($instance) { - $instance->assertInstanceOf('Jenssegers\Mongodb\Schema\Blueprint', $collection); + $instance->assertInstanceOf('Moloquent\Schema\Blueprint', $collection); }); Schema::table('newcollection', function ($collection) use ($instance) { - $instance->assertInstanceOf('Jenssegers\Mongodb\Schema\Blueprint', $collection); + $instance->assertInstanceOf('Moloquent\Schema\Blueprint', $collection); }); } diff --git a/tests/TestCase.php b/tests/TestCase.php index 63552189f..7833d8626 100644 --- a/tests/TestCase.php +++ b/tests/TestCase.php @@ -27,8 +27,8 @@ protected function getApplicationProviders($app) protected function getPackageProviders($app) { return [ - Jenssegers\Mongodb\MongodbServiceProvider::class, - Jenssegers\Mongodb\Auth\PasswordResetServiceProvider::class, + Moloquent\MongodbServiceProvider::class, + Moloquent\Auth\PasswordResetServiceProvider::class, ]; } diff --git a/tests/models/Address.php b/tests/models/Address.php index 43adff20a..47ace3a0a 100644 --- a/tests/models/Address.php +++ b/tests/models/Address.php @@ -1,6 +1,6 @@ Date: Thu, 8 Sep 2016 01:12:16 +0430 Subject: [PATCH 33/88] psr-0 --- composer.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/composer.json b/composer.json index da7e8d27f..c2a397228 100644 --- a/composer.json +++ b/composer.json @@ -37,7 +37,7 @@ "satooshi/php-coveralls": "^0.6" }, "autoload": { - "psr-4" :{ + "psr-0" :{ "Moloquent\\": "src/" } }, From 6d52a0b3b2e52e9cc07af9002cd71613f226ff05 Mon Sep 17 00:00:00 2001 From: pi0 Date: Thu, 8 Sep 2016 20:40:47 +0430 Subject: [PATCH 34/88] no version --- composer.json | 1 - 1 file changed, 1 deletion(-) diff --git a/composer.json b/composer.json index c2a397228..be710f474 100644 --- a/composer.json +++ b/composer.json @@ -1,6 +1,5 @@ { "name": "moloquent/moloquent", - "version": "5.3.0", "description": "A MongoDB based Eloquent model and Query builder for Laravel (Moloquent)", "keywords": [ "laravel", From 820d8b09e2c487f2243141ca59fecb3be430b3e2 Mon Sep 17 00:00:00 2001 From: hooman naghiee Date: Sat, 10 Sep 2016 12:26:36 +0430 Subject: [PATCH 35/88] fix psr-4 autoloading --- composer.json | 2 +- src/{Moloquent => }/Auth/DatabaseTokenRepository.php | 0 src/{Moloquent => }/Auth/PasswordBrokerManager.php | 0 src/{Moloquent => }/Auth/PasswordResetServiceProvider.php | 0 src/{Moloquent => }/Collection.php | 0 src/{Moloquent => }/Connection.php | 0 src/{Moloquent => }/Eloquent/Builder.php | 0 src/{Moloquent => }/Eloquent/HybridRelations.php | 0 src/{Moloquent => }/Eloquent/Model.php | 0 src/{Moloquent => }/Eloquent/SoftDeletes.php | 0 src/{Moloquent => }/MongodbQueueServiceProvider.php | 0 src/{Moloquent => }/MongodbServiceProvider.php | 0 src/{Moloquent => }/Query/Builder.php | 0 src/{Moloquent => }/Query/Grammar.php | 0 src/{Moloquent => }/Query/Processor.php | 0 src/{Moloquent => }/Queue/Failed/MongoFailedJobProvider.php | 0 src/{Moloquent => }/Queue/MongoConnector.php | 0 src/{Moloquent => }/Queue/MongoQueue.php | 0 src/{Moloquent => }/Relations/BelongsTo.php | 0 src/{Moloquent => }/Relations/BelongsToMany.php | 0 src/{Moloquent => }/Relations/EmbedsMany.php | 0 src/{Moloquent => }/Relations/EmbedsOne.php | 0 src/{Moloquent => }/Relations/EmbedsOneOrMany.php | 0 src/{Moloquent => }/Relations/HasMany.php | 0 src/{Moloquent => }/Relations/HasOne.php | 0 src/{Moloquent => }/Relations/HasOneOrManyTrait.php | 0 src/{Moloquent => }/Relations/MorphMany.php | 0 src/{Moloquent => }/Relations/MorphOne.php | 0 src/{Moloquent => }/Relations/MorphTo.php | 0 src/{Moloquent => }/Schema/Blueprint.php | 0 src/{Moloquent => }/Schema/Builder.php | 0 31 files changed, 1 insertion(+), 1 deletion(-) rename src/{Moloquent => }/Auth/DatabaseTokenRepository.php (100%) rename src/{Moloquent => }/Auth/PasswordBrokerManager.php (100%) rename src/{Moloquent => }/Auth/PasswordResetServiceProvider.php (100%) rename src/{Moloquent => }/Collection.php (100%) rename src/{Moloquent => }/Connection.php (100%) rename src/{Moloquent => }/Eloquent/Builder.php (100%) rename src/{Moloquent => }/Eloquent/HybridRelations.php (100%) rename src/{Moloquent => }/Eloquent/Model.php (100%) rename src/{Moloquent => }/Eloquent/SoftDeletes.php (100%) rename src/{Moloquent => }/MongodbQueueServiceProvider.php (100%) rename src/{Moloquent => }/MongodbServiceProvider.php (100%) rename src/{Moloquent => }/Query/Builder.php (100%) rename src/{Moloquent => }/Query/Grammar.php (100%) rename src/{Moloquent => }/Query/Processor.php (100%) rename src/{Moloquent => }/Queue/Failed/MongoFailedJobProvider.php (100%) rename src/{Moloquent => }/Queue/MongoConnector.php (100%) rename src/{Moloquent => }/Queue/MongoQueue.php (100%) rename src/{Moloquent => }/Relations/BelongsTo.php (100%) rename src/{Moloquent => }/Relations/BelongsToMany.php (100%) rename src/{Moloquent => }/Relations/EmbedsMany.php (100%) rename src/{Moloquent => }/Relations/EmbedsOne.php (100%) rename src/{Moloquent => }/Relations/EmbedsOneOrMany.php (100%) rename src/{Moloquent => }/Relations/HasMany.php (100%) rename src/{Moloquent => }/Relations/HasOne.php (100%) rename src/{Moloquent => }/Relations/HasOneOrManyTrait.php (100%) rename src/{Moloquent => }/Relations/MorphMany.php (100%) rename src/{Moloquent => }/Relations/MorphOne.php (100%) rename src/{Moloquent => }/Relations/MorphTo.php (100%) rename src/{Moloquent => }/Schema/Blueprint.php (100%) rename src/{Moloquent => }/Schema/Builder.php (100%) diff --git a/composer.json b/composer.json index be710f474..2706a3660 100644 --- a/composer.json +++ b/composer.json @@ -36,7 +36,7 @@ "satooshi/php-coveralls": "^0.6" }, "autoload": { - "psr-0" :{ + "psr-4" :{ "Moloquent\\": "src/" } }, diff --git a/src/Moloquent/Auth/DatabaseTokenRepository.php b/src/Auth/DatabaseTokenRepository.php similarity index 100% rename from src/Moloquent/Auth/DatabaseTokenRepository.php rename to src/Auth/DatabaseTokenRepository.php diff --git a/src/Moloquent/Auth/PasswordBrokerManager.php b/src/Auth/PasswordBrokerManager.php similarity index 100% rename from src/Moloquent/Auth/PasswordBrokerManager.php rename to src/Auth/PasswordBrokerManager.php diff --git a/src/Moloquent/Auth/PasswordResetServiceProvider.php b/src/Auth/PasswordResetServiceProvider.php similarity index 100% rename from src/Moloquent/Auth/PasswordResetServiceProvider.php rename to src/Auth/PasswordResetServiceProvider.php diff --git a/src/Moloquent/Collection.php b/src/Collection.php similarity index 100% rename from src/Moloquent/Collection.php rename to src/Collection.php diff --git a/src/Moloquent/Connection.php b/src/Connection.php similarity index 100% rename from src/Moloquent/Connection.php rename to src/Connection.php diff --git a/src/Moloquent/Eloquent/Builder.php b/src/Eloquent/Builder.php similarity index 100% rename from src/Moloquent/Eloquent/Builder.php rename to src/Eloquent/Builder.php diff --git a/src/Moloquent/Eloquent/HybridRelations.php b/src/Eloquent/HybridRelations.php similarity index 100% rename from src/Moloquent/Eloquent/HybridRelations.php rename to src/Eloquent/HybridRelations.php diff --git a/src/Moloquent/Eloquent/Model.php b/src/Eloquent/Model.php similarity index 100% rename from src/Moloquent/Eloquent/Model.php rename to src/Eloquent/Model.php diff --git a/src/Moloquent/Eloquent/SoftDeletes.php b/src/Eloquent/SoftDeletes.php similarity index 100% rename from src/Moloquent/Eloquent/SoftDeletes.php rename to src/Eloquent/SoftDeletes.php diff --git a/src/Moloquent/MongodbQueueServiceProvider.php b/src/MongodbQueueServiceProvider.php similarity index 100% rename from src/Moloquent/MongodbQueueServiceProvider.php rename to src/MongodbQueueServiceProvider.php diff --git a/src/Moloquent/MongodbServiceProvider.php b/src/MongodbServiceProvider.php similarity index 100% rename from src/Moloquent/MongodbServiceProvider.php rename to src/MongodbServiceProvider.php diff --git a/src/Moloquent/Query/Builder.php b/src/Query/Builder.php similarity index 100% rename from src/Moloquent/Query/Builder.php rename to src/Query/Builder.php diff --git a/src/Moloquent/Query/Grammar.php b/src/Query/Grammar.php similarity index 100% rename from src/Moloquent/Query/Grammar.php rename to src/Query/Grammar.php diff --git a/src/Moloquent/Query/Processor.php b/src/Query/Processor.php similarity index 100% rename from src/Moloquent/Query/Processor.php rename to src/Query/Processor.php diff --git a/src/Moloquent/Queue/Failed/MongoFailedJobProvider.php b/src/Queue/Failed/MongoFailedJobProvider.php similarity index 100% rename from src/Moloquent/Queue/Failed/MongoFailedJobProvider.php rename to src/Queue/Failed/MongoFailedJobProvider.php diff --git a/src/Moloquent/Queue/MongoConnector.php b/src/Queue/MongoConnector.php similarity index 100% rename from src/Moloquent/Queue/MongoConnector.php rename to src/Queue/MongoConnector.php diff --git a/src/Moloquent/Queue/MongoQueue.php b/src/Queue/MongoQueue.php similarity index 100% rename from src/Moloquent/Queue/MongoQueue.php rename to src/Queue/MongoQueue.php diff --git a/src/Moloquent/Relations/BelongsTo.php b/src/Relations/BelongsTo.php similarity index 100% rename from src/Moloquent/Relations/BelongsTo.php rename to src/Relations/BelongsTo.php diff --git a/src/Moloquent/Relations/BelongsToMany.php b/src/Relations/BelongsToMany.php similarity index 100% rename from src/Moloquent/Relations/BelongsToMany.php rename to src/Relations/BelongsToMany.php diff --git a/src/Moloquent/Relations/EmbedsMany.php b/src/Relations/EmbedsMany.php similarity index 100% rename from src/Moloquent/Relations/EmbedsMany.php rename to src/Relations/EmbedsMany.php diff --git a/src/Moloquent/Relations/EmbedsOne.php b/src/Relations/EmbedsOne.php similarity index 100% rename from src/Moloquent/Relations/EmbedsOne.php rename to src/Relations/EmbedsOne.php diff --git a/src/Moloquent/Relations/EmbedsOneOrMany.php b/src/Relations/EmbedsOneOrMany.php similarity index 100% rename from src/Moloquent/Relations/EmbedsOneOrMany.php rename to src/Relations/EmbedsOneOrMany.php diff --git a/src/Moloquent/Relations/HasMany.php b/src/Relations/HasMany.php similarity index 100% rename from src/Moloquent/Relations/HasMany.php rename to src/Relations/HasMany.php diff --git a/src/Moloquent/Relations/HasOne.php b/src/Relations/HasOne.php similarity index 100% rename from src/Moloquent/Relations/HasOne.php rename to src/Relations/HasOne.php diff --git a/src/Moloquent/Relations/HasOneOrManyTrait.php b/src/Relations/HasOneOrManyTrait.php similarity index 100% rename from src/Moloquent/Relations/HasOneOrManyTrait.php rename to src/Relations/HasOneOrManyTrait.php diff --git a/src/Moloquent/Relations/MorphMany.php b/src/Relations/MorphMany.php similarity index 100% rename from src/Moloquent/Relations/MorphMany.php rename to src/Relations/MorphMany.php diff --git a/src/Moloquent/Relations/MorphOne.php b/src/Relations/MorphOne.php similarity index 100% rename from src/Moloquent/Relations/MorphOne.php rename to src/Relations/MorphOne.php diff --git a/src/Moloquent/Relations/MorphTo.php b/src/Relations/MorphTo.php similarity index 100% rename from src/Moloquent/Relations/MorphTo.php rename to src/Relations/MorphTo.php diff --git a/src/Moloquent/Schema/Blueprint.php b/src/Schema/Blueprint.php similarity index 100% rename from src/Moloquent/Schema/Blueprint.php rename to src/Schema/Blueprint.php diff --git a/src/Moloquent/Schema/Builder.php b/src/Schema/Builder.php similarity index 100% rename from src/Moloquent/Schema/Builder.php rename to src/Schema/Builder.php From 80b0701730dab772e2b0a8f00a72d84e6cba9165 Mon Sep 17 00:00:00 2001 From: Craig Morris Date: Sat, 10 Sep 2016 21:21:09 +0100 Subject: [PATCH 36/88] Remove dependency on Laravel Application --- src/Jenssegers/Mongodb/Query/Builder.php | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/src/Jenssegers/Mongodb/Query/Builder.php b/src/Jenssegers/Mongodb/Query/Builder.php index 74b9ee3a6..d63cc2b77 100644 --- a/src/Jenssegers/Mongodb/Query/Builder.php +++ b/src/Jenssegers/Mongodb/Query/Builder.php @@ -96,7 +96,21 @@ public function __construct(Connection $connection, Processor $processor) $this->grammar = new Grammar; $this->connection = $connection; $this->processor = $processor; - $this->useCollections = version_compare(\Illuminate\Foundation\Application::VERSION, '5.3', '>='); + $this->useCollections = $this->shouldUseCollections(); + } + + /** + * Returns true if Laravel or Lumen >= 5.3 + * + * @return bool + */ + protected function shouldUseCollections() + { + if (function_exists('app')) { + $version = app()->version(); + $version = filter_var(explode(')', $version)[0], FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION); // lumen + return version_compare($version, '5.3', '>='); + } } /** From b399fcf267fc978cb403f3a27ca9939c3a688f9e Mon Sep 17 00:00:00 2001 From: Craig Morris Date: Sat, 10 Sep 2016 21:23:31 +0100 Subject: [PATCH 37/88] styleci --- src/Jenssegers/Mongodb/Query/Builder.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/Jenssegers/Mongodb/Query/Builder.php b/src/Jenssegers/Mongodb/Query/Builder.php index d63cc2b77..c9135a7c8 100644 --- a/src/Jenssegers/Mongodb/Query/Builder.php +++ b/src/Jenssegers/Mongodb/Query/Builder.php @@ -101,7 +101,7 @@ public function __construct(Connection $connection, Processor $processor) /** * Returns true if Laravel or Lumen >= 5.3 - * + * * @return bool */ protected function shouldUseCollections() @@ -109,7 +109,7 @@ protected function shouldUseCollections() if (function_exists('app')) { $version = app()->version(); $version = filter_var(explode(')', $version)[0], FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION); // lumen - return version_compare($version, '5.3', '>='); + return version_compare($version, '5.3', '>='); } } From 7d35227fc25777e9d4f9303c707c913edf837eee Mon Sep 17 00:00:00 2001 From: Pooya Parsa Date: Sun, 11 Sep 2016 08:57:58 +0000 Subject: [PATCH 38/88] Applied fixes from StyleCI [ci skip] [skip ci] --- src/Auth/DatabaseTokenRepository.php | 16 +- src/Auth/PasswordBrokerManager.php | 7 +- src/Auth/PasswordResetServiceProvider.php | 4 +- src/Collection.php | 13 +- src/Connection.php | 39 ++-- src/Eloquent/Builder.php | 48 +++-- src/Eloquent/HybridRelations.php | 101 ++++++----- src/Eloquent/Model.php | 129 ++++++++----- src/Eloquent/SoftDeletes.php | 4 +- src/MongodbQueueServiceProvider.php | 4 +- src/MongodbServiceProvider.php | 4 +- src/Query/Builder.php | 191 ++++++++++++-------- src/Query/Grammar.php | 4 +- src/Query/Processor.php | 4 +- src/Queue/Failed/MongoFailedJobProvider.php | 22 ++- src/Queue/MongoConnector.php | 10 +- src/Queue/MongoQueue.php | 22 ++- src/Relations/BelongsTo.php | 14 +- src/Relations/BelongsToMany.php | 57 +++--- src/Relations/EmbedsMany.php | 64 ++++--- src/Relations/EmbedsOne.php | 26 ++- src/Relations/EmbedsOneOrMany.php | 61 ++++--- src/Relations/HasMany.php | 18 +- src/Relations/HasOne.php | 18 +- src/Relations/HasOneOrManyTrait.php | 19 +- src/Relations/MorphMany.php | 4 +- src/Relations/MorphOne.php | 4 +- src/Relations/MorphTo.php | 10 +- src/Schema/Blueprint.php | 68 ++++--- src/Schema/Builder.php | 43 +++-- tests/CollectionTest.php | 4 +- tests/EmbeddedRelationsTest.php | 66 +++---- tests/ModelTest.php | 30 +-- tests/MysqlRelationsTest.php | 8 +- tests/QueryBuilderTest.php | 26 +-- tests/RelationsWithMongoIdTest.php | 14 +- tests/SchemaTest.php | 2 +- tests/SeederTest.php | 2 +- tests/TestCase.php | 8 +- tests/models/Book.php | 1 - tests/models/MysqlBook.php | 2 +- tests/models/MysqlRole.php | 2 +- tests/models/MysqlUser.php | 2 +- tests/models/User.php | 2 +- 44 files changed, 710 insertions(+), 487 deletions(-) diff --git a/src/Auth/DatabaseTokenRepository.php b/src/Auth/DatabaseTokenRepository.php index d5903e293..bde6f1307 100644 --- a/src/Auth/DatabaseTokenRepository.php +++ b/src/Auth/DatabaseTokenRepository.php @@ -1,17 +1,20 @@ -collection->getCollectionName() . '.' . $method . '(' . implode(',', $query) . ')'; + $queryString = $this->collection->getCollectionName().'.'.$method.'('.implode(',', $query).')'; $this->connection->logQuery($queryString, [], $time); } diff --git a/src/Connection.php b/src/Connection.php index 4bd6138a7..8e67babc5 100644 --- a/src/Connection.php +++ b/src/Connection.php @@ -1,4 +1,6 @@ -hasCast($relation->getHasCompareKey(), null, 'set')) { $id = $relationModel->castAttribute($relation->getHasCompareKey(), $id, 'set'); } + return $id; }, array_keys($relationCount)); @@ -220,7 +229,8 @@ protected function addHasWhere(EloquentBuilder $hasQuery, Relation $relation, $o /** * Create a raw database expression. * - * @param closure $expression + * @param closure $expression + * * @return mixed */ public function raw($expression = null) @@ -231,12 +241,14 @@ public function raw($expression = null) // Convert MongoCursor results to a collection of models. if ($results instanceof Cursor) { $results = iterator_to_array($results, false); + return $this->model->hydrate($results); } // Convert Mongo BSONDocument to a single object. elseif ($results instanceof BSONDocument) { $results = $results->getArrayCopy(); + return $this->model->newFromBuilder((array) $results); } diff --git a/src/Eloquent/HybridRelations.php b/src/Eloquent/HybridRelations.php index a33328a2b..4f8d7a477 100644 --- a/src/Eloquent/HybridRelations.php +++ b/src/Eloquent/HybridRelations.php @@ -1,34 +1,37 @@ -getForeignKey(); - $instance = new $related; + $instance = new $related(); $localKey = $localKey ?: $this->getKeyName(); @@ -38,21 +41,22 @@ public function hasOne($related, $foreignKey = null, $localKey = null) /** * Define a polymorphic one-to-one relationship. * - * @param string $related - * @param string $name - * @param string $type - * @param string $id - * @param string $localKey + * @param string $related + * @param string $name + * @param string $type + * @param string $id + * @param string $localKey + * * @return \Illuminate\Database\Eloquent\Relations\MorphOne */ public function morphOne($related, $name, $type = null, $id = null, $localKey = null) { // Check if it is a relation with an original model. - if (! is_subclass_of($related, 'Moloquent\Eloquent\Model')) { + if (!is_subclass_of($related, 'Moloquent\Eloquent\Model')) { return parent::morphOne($related, $name, $type, $id, $localKey); } - $instance = new $related; + $instance = new $related(); list($type, $id) = $this->getMorphs($name, $type, $id); @@ -66,21 +70,22 @@ public function morphOne($related, $name, $type = null, $id = null, $localKey = /** * Define a one-to-many relationship. * - * @param string $related - * @param string $foreignKey - * @param string $localKey + * @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. - if (! is_subclass_of($related, 'Moloquent\Eloquent\Model')) { + if (!is_subclass_of($related, 'Moloquent\Eloquent\Model')) { return parent::hasMany($related, $foreignKey, $localKey); } $foreignKey = $foreignKey ?: $this->getForeignKey(); - $instance = new $related; + $instance = new $related(); $localKey = $localKey ?: $this->getKeyName(); @@ -90,21 +95,22 @@ public function hasMany($related, $foreignKey = null, $localKey = null) /** * Define a polymorphic one-to-many relationship. * - * @param string $related - * @param string $name - * @param string $type - * @param string $id - * @param string $localKey + * @param string $related + * @param string $name + * @param string $type + * @param string $id + * @param string $localKey + * * @return \Illuminate\Database\Eloquent\Relations\MorphMany */ public function morphMany($related, $name, $type = null, $id = null, $localKey = null) { // Check if it is a relation with an original model. - if (! is_subclass_of($related, 'Moloquent\Eloquent\Model')) { + if (!is_subclass_of($related, 'Moloquent\Eloquent\Model')) { return parent::morphMany($related, $name, $type, $id, $localKey); } - $instance = new $related; + $instance = new $related(); // Here we will gather up the morph type and ID for the relationship so that we // can properly query the intermediate table of a relation. Finally, we will @@ -121,10 +127,11 @@ public function morphMany($related, $name, $type = null, $id = null, $localKey = /** * Define an inverse one-to-one or many relationship. * - * @param string $related - * @param string $foreignKey - * @param string $otherKey - * @param string $relation + * @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) @@ -139,7 +146,7 @@ public function belongsTo($related, $foreignKey = null, $otherKey = null, $relat } // Check if it is a relation with an original model. - if (! is_subclass_of($related, 'Moloquent\Eloquent\Model')) { + if (!is_subclass_of($related, 'Moloquent\Eloquent\Model')) { return parent::belongsTo($related, $foreignKey, $otherKey, $relation); } @@ -147,10 +154,10 @@ public function belongsTo($related, $foreignKey = null, $otherKey = null, $relat // foreign key name by using the name of the relationship function, which // when combined with an "_id" should conventionally match the columns. if (is_null($foreignKey)) { - $foreignKey = Str::snake($relation) . '_id'; + $foreignKey = Str::snake($relation).'_id'; } - $instance = new $related; + $instance = new $related(); // Once we have the foreign key names, we'll just create a new Eloquent query // for the related models and returns the relationship instance which will @@ -165,9 +172,10 @@ public function belongsTo($related, $foreignKey = null, $otherKey = null, $relat /** * Define a polymorphic, inverse one-to-one or many relationship. * - * @param string $name - * @param string $type - * @param string $id + * @param string $name + * @param string $type + * @param string $id + * * @return \Illuminate\Database\Eloquent\Relations\MorphTo */ public function morphTo($name = null, $type = null, $id = null) @@ -198,7 +206,7 @@ public function morphTo($name = null, $type = null, $id = null) else { $class = $this->getActualClassNameForMorph($class); - $instance = new $class; + $instance = new $class(); return new MorphTo( $instance->newQuery(), $this, $id, $instance->getKeyName(), $type, $name @@ -209,11 +217,12 @@ public function morphTo($name = null, $type = null, $id = null) /** * Define a many-to-many relationship. * - * @param string $related - * @param string $collection - * @param string $foreignKey - * @param string $otherKey - * @param string $relation + * @param string $related + * @param string $collection + * @param string $foreignKey + * @param string $otherKey + * @param string $relation + * * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany */ public function belongsToMany($related, $collection = null, $foreignKey = null, $otherKey = null, $relation = null) @@ -226,18 +235,18 @@ public function belongsToMany($related, $collection = null, $foreignKey = null, } // Check if it is a relation with an original model. - if (! is_subclass_of($related, 'Moloquent\Eloquent\Model')) { + if (!is_subclass_of($related, 'Moloquent\Eloquent\Model')) { return parent::belongsToMany($related, $collection, $foreignKey, $otherKey, $relation); } // First, we'll need to determine the foreign key and "other key" for the // relationship. Once we have determined the keys we'll make the query // instances as well as the relationship instances we need for this. - $foreignKey = $foreignKey ?: $this->getForeignKey() . 's'; + $foreignKey = $foreignKey ?: $this->getForeignKey().'s'; - $instance = new $related; + $instance = new $related(); - $otherKey = $otherKey ?: $instance->getForeignKey() . 's'; + $otherKey = $otherKey ?: $instance->getForeignKey().'s'; // If no table name was provided, we can guess it by concatenating the two // models using underscores in alphabetical order. The two model names diff --git a/src/Eloquent/Model.php b/src/Eloquent/Model.php index da4517a5f..00914b393 100644 --- a/src/Eloquent/Model.php +++ b/src/Eloquent/Model.php @@ -1,4 +1,6 @@ -attributes)) { + if (!$value and array_key_exists('_id', $this->attributes)) { $value = $this->attributes['_id']; } @@ -79,10 +82,11 @@ public function getQualifiedKeyName() /** * Define an embedded one-to-many relationship. * - * @param string $related - * @param string $localKey - * @param string $foreignKey - * @param string $relation + * @param string $related + * @param string $localKey + * @param string $foreignKey + * @param string $relation + * * @return \Moloquent\Relations\EmbedsMany */ protected function embedsMany($related, $localKey = null, $foreignKey = null, $relation = null) @@ -106,7 +110,7 @@ protected function embedsMany($related, $localKey = null, $foreignKey = null, $r $query = $this->newQuery(); - $instance = new $related; + $instance = new $related(); return new EmbedsMany($query, $this, $instance, $localKey, $foreignKey, $relation); } @@ -114,10 +118,11 @@ protected function embedsMany($related, $localKey = null, $foreignKey = null, $r /** * Define an embedded one-to-many relationship. * - * @param string $related - * @param string $localKey - * @param string $foreignKey - * @param string $relation + * @param string $related + * @param string $localKey + * @param string $foreignKey + * @param string $relation + * * @return \Moloquent\Relations\EmbedsOne */ protected function embedsOne($related, $localKey = null, $foreignKey = null, $relation = null) @@ -141,7 +146,7 @@ protected function embedsOne($related, $localKey = null, $foreignKey = null, $re $query = $this->newQuery(); - $instance = new $related; + $instance = new $related(); return new EmbedsOne($query, $this, $instance, $localKey, $foreignKey, $relation); } @@ -149,7 +154,8 @@ protected function embedsOne($related, $localKey = null, $foreignKey = null, $re /** * Convert a DateTime to a storable UTCDateTime object. * - * @param DateTime|int $value + * @param DateTime|int $value + * * @return UTCDateTime */ public function fromDateTime($value) @@ -160,7 +166,7 @@ public function fromDateTime($value) } // Let Eloquent convert the value to a DateTime instance. - if (! $value instanceof DateTime) { + if (!$value instanceof DateTime) { $value = parent::asDateTime($value); } @@ -170,7 +176,8 @@ public function fromDateTime($value) /** * Return a timestamp as DateTime object. * - * @param mixed $value + * @param mixed $value + * * @return DateTime */ protected function asDateTime($value) @@ -216,7 +223,8 @@ public function getTable() /** * Get an attribute from the model. * - * @param string $key + * @param string $key + * * @return mixed */ public function getAttribute($key) @@ -235,7 +243,7 @@ public function getAttribute($key) $method = new ReflectionMethod(get_called_class(), $camelKey); // Ensure the method is not static to avoid conflicting with Eloquent methods. - if (! $method->isStatic()) { + if (!$method->isStatic()) { $relations = $this->$camelKey(); // This attribute matches an embedsOne or embedsMany relation so we need @@ -272,7 +280,8 @@ public function getAttribute($key) /** * Get an attribute from the $attributes array. * - * @param string $key + * @param string $key + * * @return mixed */ protected function getAttributeFromArray($key) @@ -292,8 +301,8 @@ protected function getAttributeFromArray($key) /** * Set a given attribute on the model. * - * @param string $key - * @param mixed $value + * @param string $key + * @param mixed $value */ public function setAttribute($key, $value) { @@ -348,7 +357,8 @@ public function attributesToArray() /** * Determine if the new and old values for a given key are numerically equivalent. * - * @param string $key + * @param string $key + * * @return bool */ protected function originalIsNumericallyEquivalent($key) @@ -370,12 +380,13 @@ protected function originalIsNumericallyEquivalent($key) /** * Remove one or more fields. * - * @param mixed $columns + * @param mixed $columns + * * @return int */ public function drop($columns) { - if (! is_array($columns)) { + if (!is_array($columns)) { $columns = [$columns]; } @@ -405,7 +416,7 @@ public function push() } // Do batch push by default. - if (! is_array($values)) { + if (!is_array($values)) { $values = [$values]; } @@ -422,14 +433,15 @@ public function push() /** * Remove one or more values from an array. * - * @param string $column - * @param mixed $values + * @param string $column + * @param mixed $values + * * @return mixed */ public function pull($column, $values) { // Do batch pull by default. - if (! is_array($values)) { + if (!is_array($values)) { $values = [$values]; } @@ -443,9 +455,9 @@ public function pull($column, $values) /** * Append one or more values to the underlying attribute value and sync with original. * - * @param string $column - * @param array $values - * @param bool $unique + * @param string $column + * @param array $values + * @param bool $unique */ protected function pushAttributeValues($column, array $values, $unique = false) { @@ -468,8 +480,8 @@ protected function pushAttributeValues($column, array $values, $unique = false) /** * Remove one or more values to the underlying attribute value and sync with original. * - * @param string $column - * @param array $values + * @param string $column + * @param array $values */ protected function pullAttributeValues($column, array $values) { @@ -491,7 +503,7 @@ protected function pullAttributeValues($column, array $values) /** * Set the parent relation. * - * @param \Illuminate\Database\Eloquent\Relations\Relation $relation + * @param \Illuminate\Database\Eloquent\Relations\Relation $relation */ public function setParentRelation(Relation $relation) { @@ -511,7 +523,8 @@ public function getParentRelation() /** * Create a new Eloquent query builder for the model. * - * @param \Moloquent\Query\Builder $query + * @param \Moloquent\Query\Builder $query + * * @return \Moloquent\Eloquent\Builder|static */ public function newEloquentBuilder($query) @@ -530,11 +543,12 @@ protected function newBaseQueryBuilder() return new QueryBuilder($connection, $connection->getPostProcessor()); } - + /** - * We just return original key here in order to support keys in dot-notation + * We just return original key here in order to support keys in dot-notation. + * + * @param string $key * - * @param string $key * @return string */ protected function removeTableFromKey($key) @@ -545,8 +559,9 @@ protected function removeTableFromKey($key) /** * Handle dynamic method calls into the method. * - * @param string $method - * @param array $parameters + * @param string $method + * @param array $parameters + * * @return mixed */ public function __call($method, $parameters) @@ -560,15 +575,18 @@ public function __call($method, $parameters) } /** - * setter for casts + * setter for casts. + * * @param $cast * @param string $castType + * * @return void */ public function setCasts($cast, $castType = 'get') { if ($castType == 'set') { $this->saveCasts = $cast; + return; } $this->casts = $cast; @@ -578,6 +596,7 @@ public function setCasts($cast, $castType = 'get') * Get the casts array. * * @param string $castType + * * @return array */ public function getCasts($castType = 'get') @@ -585,14 +604,16 @@ public function getCasts($castType = 'get') if ($castType == 'set') { return $this->saveCasts; } + return $this->casts; } /** * Get the type of save cast for a model attribute. * - * @param string $key + * @param string $key * @param string $castType + * * @return string */ protected function getCastType($key, $castType = 'get') @@ -603,9 +624,10 @@ protected function getCastType($key, $castType = 'get') /** * Determine whether an attribute should be cast to a native type. * - * @param string $key - * @param array|string|null $types - * @param string $castType + * @param string $key + * @param array|string|null $types + * @param string $castType + * * @return bool */ public function hasCast($key, $types = null, $castType = 'get') @@ -616,6 +638,7 @@ public function hasCast($key, $types = null, $castType = 'get') return false; } + /** * check if driver uses mongoId in relations. * @@ -629,9 +652,10 @@ public function useMongoId() /** * Cast an attribute to a mongo type. * - * @param string $key - * @param mixed $value + * @param string $key + * @param mixed $value * @param string $castType + * * @return mixed */ public function castAttribute($key, $value, $castType = 'get') @@ -672,9 +696,10 @@ public function castAttribute($key, $value, $castType = 'get') } /** - * convert value into ObjectID if its possible + * convert value into ObjectID if its possible. * * @param $value + * * @return UTCDatetime */ protected function asMongoID($value) @@ -682,12 +707,15 @@ protected function asMongoID($value) if (is_string($value) and strlen($value) === 24 and ctype_xdigit($value)) { return new ObjectID($value); } + return $value; } /** - * convert value into UTCDatetime + * convert value into UTCDatetime. + * * @param $value + * * @return UTCDatetime */ protected function asMongoDate($value) @@ -701,7 +729,7 @@ protected function asMongoDate($value) /** * add relation that ended with _id into objectId - * if config allow it + * if config allow it. * * @param $key */ @@ -709,6 +737,7 @@ public function setRelationCast($key) { if ($key == '_id') { $this->saveCasts['_id'] = 'ObjectID'; + return; } if ($this->useMongoId()) { diff --git a/src/Eloquent/SoftDeletes.php b/src/Eloquent/SoftDeletes.php index ee99fa5a9..028ae3750 100644 --- a/src/Eloquent/SoftDeletes.php +++ b/src/Eloquent/SoftDeletes.php @@ -1,4 +1,6 @@ -= 5.3 ) + * Check if we need to return Collections instead of plain arrays (laravel >= 5.3 ). * - * @var boolean + * @var bool */ protected $useCollections; @@ -93,14 +95,14 @@ class Builder extends BaseBuilder */ public function __construct(Connection $connection, Processor $processor) { - $this->grammar = new Grammar; + $this->grammar = new Grammar(); $this->connection = $connection; $this->processor = $processor; $this->useCollections = $this->shouldUseCollections(); } - + /** - * Returns true if Laravel or Lumen >= 5.3 + * Returns true if Laravel or Lumen >= 5.3. * * @return bool */ @@ -116,7 +118,8 @@ protected function shouldUseCollections() /** * Set the projections. * - * @param array $columns + * @param array $columns + * * @return $this */ public function project($columns) @@ -129,7 +132,8 @@ public function project($columns) /** * Set the cursor timeout in seconds. * - * @param int $seconds + * @param int $seconds + * * @return $this */ public function timeout($seconds) @@ -142,7 +146,8 @@ public function timeout($seconds) /** * Set the cursor hint. * - * @param mixed $index + * @param mixed $index + * * @return $this */ public function hint($index) @@ -155,8 +160,9 @@ public function hint($index) /** * Execute a query for a single record by ID. * - * @param mixed $id - * @param array $columns + * @param mixed $id + * @param array $columns + * * @return mixed */ public function find($id, $columns = []) @@ -167,7 +173,8 @@ public function find($id, $columns = []) /** * Execute the query as a "select" statement. * - * @param array $columns + * @param array $columns + * * @return array|static[]|Collection */ public function get($columns = []) @@ -178,7 +185,8 @@ public function get($columns = []) /** * Execute the query as a fresh "select" statement. * - * @param array $columns + * @param array $columns + * * @return array|static[]|Collection */ public function getFresh($columns = []) @@ -206,18 +214,18 @@ public function getFresh($columns = []) // Add grouping columns to the $group part of the aggregation pipeline. if ($this->groups) { foreach ($this->groups as $column) { - $group['_id'][$column] = '$' . $column; + $group['_id'][$column] = '$'.$column; // When grouping, also add the $last operator to each grouped field, // this mimics MySQL's behaviour a bit. - $group[$column] = ['$last' => '$' . $column]; + $group[$column] = ['$last' => '$'.$column]; } // Do the same for other columns that are selected. foreach ($this->columns as $column) { $key = str_replace('.', '_', $column); - $group[$key] = ['$last' => '$' . $column]; + $group[$key] = ['$last' => '$'.$column]; } } @@ -240,7 +248,7 @@ public function getFresh($columns = []) } // Pass other functions directly. else { - $group['aggregate'] = ['$' . $function => '$' . $column]; + $group['aggregate'] = ['$'.$function => '$'.$column]; } } } @@ -266,7 +274,7 @@ public function getFresh($columns = []) // apply unwinds for subdocument array aggregation foreach ($unwinds as $unwind) { - $pipeline[] = ['$unwind' => '$' . $unwind]; + $pipeline[] = ['$unwind' => '$'.$unwind]; } if ($group) { @@ -354,6 +362,7 @@ public function getFresh($columns = []) // Return results as an array with numeric keys $results = iterator_to_array($cursor, false); + return $this->useCollections ? new Collection($results) : $results; } } @@ -383,8 +392,9 @@ public function generateCacheKey() /** * Execute an aggregate function on the database. * - * @param string $function - * @param array $columns + * @param string $function + * @param array $columns + * * @return mixed */ public function aggregate($function, $columns = []) @@ -413,7 +423,7 @@ public function aggregate($function, $columns = []) */ public function exists() { - return ! is_null($this->first()); + return !is_null($this->first()); } /** @@ -435,8 +445,9 @@ public function distinct($column = false) /** * Add an "order by" clause to the query. * - * @param string $column - * @param string $direction + * @param string $column + * @param string $direction + * * @return Builder */ public function orderBy($column, $direction = 'asc') @@ -457,10 +468,11 @@ public function orderBy($column, $direction = 'asc') /** * Add a where between statement to the query. * - * @param string $column - * @param array $values - * @param string $boolean - * @param bool $not + * @param string $column + * @param array $values + * @param string $boolean + * @param bool $not + * * @return Builder */ public function whereBetween($column, array $values, $boolean = 'and', $not = false) @@ -475,8 +487,9 @@ public function whereBetween($column, array $values, $boolean = 'and', $not = fa /** * Set the limit and offset for a given page. * - * @param int $page - * @param int $perPage + * @param int $page + * @param int $perPage + * * @return \Illuminate\Database\Query\Builder|static */ public function forPage($page, $perPage = 15) @@ -489,7 +502,8 @@ public function forPage($page, $perPage = 15) /** * Insert a new record into the database. * - * @param array $values + * @param array $values + * * @return bool */ public function insert(array $values) @@ -501,27 +515,28 @@ public function insert(array $values) foreach ($values as $value) { // As soon as we find a value that is not an array we assume the user is // inserting a single document. - if (! is_array($value)) { + if (!is_array($value)) { $batch = false; break; } } - if (! $batch) { + if (!$batch) { $values = [$values]; } // Batch insert $result = $this->collection->insertMany($values); - return (1 == (int) $result->isAcknowledged()); + return 1 == (int) $result->isAcknowledged(); } /** * Insert a new record and get the value of the primary key. * - * @param array $values - * @param string $sequence + * @param array $values + * @param string $sequence + * * @return int */ public function insertGetId(array $values, $sequence = null) @@ -541,14 +556,15 @@ public function insertGetId(array $values, $sequence = null) /** * Update a record in the database. * - * @param array $values - * @param array $options + * @param array $values + * @param array $options + * * @return int */ public function update(array $values, array $options = []) { // Use $set as default operator. - if (! starts_with(key($values), '$')) { + if (!starts_with(key($values), '$')) { $values = ['$set' => $values]; } @@ -558,16 +574,17 @@ public function update(array $values, array $options = []) /** * Increment a column's value by a given amount. * - * @param string $column - * @param int $amount - * @param array $extra + * @param string $column + * @param int $amount + * @param array $extra + * * @return int */ public function increment($column, $amount = 1, array $extra = [], array $options = []) { $query = ['$inc' => [$column => $amount]]; - if (! empty($extra)) { + if (!empty($extra)) { $query['$set'] = $extra; } @@ -584,9 +601,10 @@ public function increment($column, $amount = 1, array $extra = [], array $option /** * Decrement a column's value by a given amount. * - * @param string $column - * @param int $amount - * @param array $extra + * @param string $column + * @param int $amount + * @param array $extra + * * @return int */ public function decrement($column, $amount = 1, array $extra = [], array $options = []) @@ -597,8 +615,9 @@ public function decrement($column, $amount = 1, array $extra = [], array $option /** * Get an array with the values of a given column. * - * @param string $column - * @param string|null $key + * @param string $column + * @param string|null $key + * * @return array */ public function pluck($column, $key = null) @@ -609,18 +628,21 @@ public function pluck($column, $key = null) if ($key == '_id') { $results = $results->map(function ($item) { $item['_id'] = (string) $item['_id']; + return $item; }); } $p = Arr::pluck($results, $column, $key); + return $this->useCollections ? new Collection($p) : $p; } /** * Delete a record from the database. * - * @param mixed $id + * @param mixed $id + * * @return int */ public function delete($id = null) @@ -637,7 +659,8 @@ public function delete($id = null) /** * Set the collection which the query is targeting. * - * @param string $collection + * @param string $collection + * * @return Builder */ public function from($collection) @@ -656,15 +679,17 @@ public function truncate() { $result = $this->collection->drop(); - return (1 == (int) $result->ok); + return 1 == (int) $result->ok; } /** * Get an array with the values of a given column. * * @deprecated - * @param string $column - * @param string $key + * + * @param string $column + * @param string $key + * * @return array */ public function lists($column, $key = null) @@ -675,7 +700,8 @@ public function lists($column, $key = null) /** * Create a raw database expression. * - * @param closure $expression + * @param closure $expression + * * @return mixed */ public function raw($expression = null) @@ -686,7 +712,7 @@ public function raw($expression = null) } // Create an expression for the given value - elseif (! is_null($expression)) { + elseif (!is_null($expression)) { return new Expression($expression); } @@ -697,8 +723,9 @@ public function raw($expression = null) /** * Append one or more values to an array. * - * @param mixed $column - * @param mixed $value + * @param mixed $column + * @param mixed $value + * * @return int */ public function push($column, $value = null, $unique = false) @@ -723,8 +750,9 @@ public function push($column, $value = null, $unique = false) /** * Remove one or more values from an array. * - * @param mixed $column - * @param mixed $value + * @param mixed $column + * @param mixed $value + * * @return int */ public function pull($column, $value = null) @@ -747,12 +775,13 @@ public function pull($column, $value = null) /** * Remove one or more fields. * - * @param mixed $columns + * @param mixed $columns + * * @return int */ public function drop($columns) { - if (! is_array($columns)) { + if (!is_array($columns)) { $columns = [$columns]; } @@ -774,20 +803,21 @@ public function drop($columns) */ public function newQuery() { - return new Builder($this->connection, $this->processor); + return new self($this->connection, $this->processor); } /** * Perform an update query. * - * @param array $query - * @param array $options + * @param array $query + * @param array $options + * * @return int */ protected function performUpdate($query, array $options = []) { // Update multiple items by default. - if (! array_key_exists('multiple', $options)) { + if (!array_key_exists('multiple', $options)) { $options['multiple'] = true; } @@ -803,7 +833,8 @@ protected function performUpdate($query, array $options = []) /** * Convert a key to ObjectID if needed. * - * @param mixed $id + * @param mixed $id + * * @return mixed */ public function convertKey($id) @@ -818,13 +849,14 @@ public function convertKey($id) /** * Add a basic where clause to the query. * - * @param string $column - * @param string $operator - * @param mixed $value - * @param string $boolean - * @return \Illuminate\Database\Query\Builder|static + * @param string $column + * @param string $operator + * @param mixed $value + * @param string $boolean * * @throws \InvalidArgumentException + * + * @return \Illuminate\Database\Query\Builder|static */ public function where($column, $operator = null, $value = null, $boolean = 'and') { @@ -938,11 +970,11 @@ protected function compileWhereBasic($where) $regex = preg_replace('#(^|[^\\\])%#', '$1.*', preg_quote($value)); // Convert like to regular expression. - if (! starts_with($value, '%')) { - $regex = '^' . $regex; + if (!starts_with($value, '%')) { + $regex = '^'.$regex; } - if (! ends_with($value, '%')) { - $regex = $regex . '$'; + if (!ends_with($value, '%')) { + $regex = $regex.'$'; } $value = new Regex($regex, 'i'); @@ -951,7 +983,7 @@ protected function compileWhereBasic($where) // Manipulate regexp operations. elseif (in_array($operator, ['regexp', 'not regexp', 'regex', 'not regex'])) { // Automatically convert regular expression strings to Regex objects. - if (! $value instanceof Regex) { + if (!$value instanceof Regex) { $e = explode('/', $value); $flag = end($e); $regstr = substr($value, 1, -(strlen($flag) + 1)); @@ -965,12 +997,12 @@ protected function compileWhereBasic($where) } } - if (! isset($operator) or $operator == '=') { + if (!isset($operator) or $operator == '=') { $query = [$column => $value]; } elseif (array_key_exists($operator, $this->conversion)) { $query = [$column => [$this->conversion[$operator] => $value]]; } else { - $query = [$column => ['$' . $operator => $value]]; + $query = [$column => ['$'.$operator => $value]]; } return $query; @@ -1050,8 +1082,9 @@ protected function compileWhereRaw($where) /** * Handle dynamic method calls into the method. * - * @param string $method - * @param array $parameters + * @param string $method + * @param array $parameters + * * @return mixed */ public function __call($method, $parameters) diff --git a/src/Query/Grammar.php b/src/Query/Grammar.php index 3b6373c1a..ca50914cc 100644 --- a/src/Query/Grammar.php +++ b/src/Query/Grammar.php @@ -1,4 +1,6 @@ -getTimestamp(); - $this->getTable()->insert(compact('connection', 'queue', 'payload', 'failed_at','exception')); + $this->getTable()->insert(compact('connection', 'queue', 'payload', 'failed_at', 'exception')); } /** @@ -32,6 +35,7 @@ public function all() $all = array_map(function ($job) { $job['id'] = (string) $job['_id']; + return $job; }, $all); @@ -41,7 +45,8 @@ public function all() /** * Get a single failed job. * - * @param mixed $id + * @param mixed $id + * * @return array */ public function find($id) @@ -56,7 +61,8 @@ public function find($id) /** * Delete a single failed job from storage. * - * @param mixed $id + * @param mixed $id + * * @return bool */ public function forget($id) diff --git a/src/Queue/MongoConnector.php b/src/Queue/MongoConnector.php index fcd1cdf77..27ae6171e 100644 --- a/src/Queue/MongoConnector.php +++ b/src/Queue/MongoConnector.php @@ -1,4 +1,6 @@ -setRelation($relation, $dictionary[(string) $model->$foreign]); } } + return $models; } } diff --git a/src/Relations/BelongsToMany.php b/src/Relations/BelongsToMany.php index 53f8d54c9..e3599110f 100644 --- a/src/Relations/BelongsToMany.php +++ b/src/Relations/BelongsToMany.php @@ -1,4 +1,6 @@ - $attributes) { - if (! is_array($attributes)) { + if (!is_array($attributes)) { list($id, $attributes) = [$attributes, []]; } $results[$id] = $attributes; } + return $results; } } diff --git a/src/Relations/EmbedsMany.php b/src/Relations/EmbedsMany.php index 2352aec26..4279e5c80 100644 --- a/src/Relations/EmbedsMany.php +++ b/src/Relations/EmbedsMany.php @@ -1,4 +1,6 @@ -getKeyName() == '_id' and ! $model->getKey()) { - $model->setAttribute('_id', new ObjectID); + if ($model->getKeyName() == '_id' and !$model->getKey()) { + $model->setAttribute('_id', new ObjectID()); } // For deeply nested documents, let the parent handle the changes. @@ -66,7 +69,8 @@ public function performInsert(Model $model) /** * Save an existing model and attach it to the parent model. * - * @param \Illuminate\Database\Eloquent\Model $model + * @param \Illuminate\Database\Eloquent\Model $model + * * @return Model|bool */ public function performUpdate(Model $model) @@ -82,10 +86,10 @@ public function performUpdate(Model $model) $foreignKey = $this->getForeignKeyValue($model); // Use array dot notation for better update behavior. - $values = array_dot($model->getDirty(), $this->localKey . '.$.'); + $values = array_dot($model->getDirty(), $this->localKey.'.$.'); // Update document in database. - $result = $this->getBaseQuery()->where($this->localKey . '.' . $model->getKeyName(), $foreignKey) + $result = $this->getBaseQuery()->where($this->localKey.'.'.$model->getKeyName(), $foreignKey) ->update($values); // Attach the model to its parent. @@ -99,7 +103,8 @@ public function performUpdate(Model $model) /** * Delete an existing model and detach it from the parent model. * - * @param Model $model + * @param Model $model + * * @return int */ public function performDelete(Model $model) @@ -126,12 +131,13 @@ public function performDelete(Model $model) /** * Associate the model instance to the given parent, without saving it to the database. * - * @param \Illuminate\Database\Eloquent\Model $model + * @param \Illuminate\Database\Eloquent\Model $model + * * @return \Illuminate\Database\Eloquent\Model */ public function associate(Model $model) { - if (! $this->contains($model)) { + if (!$this->contains($model)) { return $this->associateNew($model); } else { return $this->associateExisting($model); @@ -141,7 +147,8 @@ public function associate(Model $model) /** * Dissociate the model instance from the given parent, without saving it to the database. * - * @param mixed $ids + * @param mixed $ids + * * @return int */ public function dissociate($ids = []) @@ -170,7 +177,8 @@ public function dissociate($ids = []) /** * Destroy the embedded models for the given IDs. * - * @param mixed $ids + * @param mixed $ids + * * @return int */ public function destroy($ids = []) @@ -212,7 +220,8 @@ public function delete() /** * Destroy alias. * - * @param mixed $ids + * @param mixed $ids + * * @return int */ public function detach($ids = []) @@ -223,7 +232,8 @@ public function detach($ids = []) /** * Save alias. * - * @param \Illuminate\Database\Eloquent\Model $model + * @param \Illuminate\Database\Eloquent\Model $model + * * @return \Illuminate\Database\Eloquent\Model */ public function attach(Model $model) @@ -234,14 +244,15 @@ public function attach(Model $model) /** * Associate a new model instance to the given parent, without saving it to the database. * - * @param \Illuminate\Database\Eloquent\Model $model + * @param \Illuminate\Database\Eloquent\Model $model + * * @return \Illuminate\Database\Eloquent\Model */ protected function associateNew($model) { // Create a new key if needed. - if (! $model->getAttribute('_id')) { - $model->setAttribute('_id', new ObjectID); + if (!$model->getAttribute('_id')) { + $model->setAttribute('_id', new ObjectID()); } $records = $this->getEmbedded(); @@ -255,7 +266,8 @@ protected function associateNew($model) /** * Associate an existing model instance to the given parent, without saving it to the database. * - * @param \Illuminate\Database\Eloquent\Model $model + * @param \Illuminate\Database\Eloquent\Model $model + * * @return \Illuminate\Database\Eloquent\Model */ protected function associateExisting($model) @@ -281,7 +293,8 @@ protected function associateExisting($model) /** * Get a paginator for the "select" statement. * - * @param int $perPage + * @param int $perPage + * * @return \Illuminate\Pagination\Paginator */ public function paginate($perPage = null) @@ -314,11 +327,11 @@ protected function getEmbedded() /** * Set the embedded records array. * - * @param array $models + * @param array $models */ protected function setEmbedded($models) { - if (! is_array($models)) { + if (!is_array($models)) { $models = [$models]; } @@ -328,8 +341,9 @@ protected function setEmbedded($models) /** * Handle dynamic method calls to the relationship. * - * @param string $method - * @param array $parameters + * @param string $method + * @param array $parameters + * * @return mixed */ public function __call($method, $parameters) diff --git a/src/Relations/EmbedsOne.php b/src/Relations/EmbedsOne.php index 5d41ffe4c..6c22315af 100644 --- a/src/Relations/EmbedsOne.php +++ b/src/Relations/EmbedsOne.php @@ -1,4 +1,6 @@ -getKeyName() == '_id' and ! $model->getKey()) { - $model->setAttribute('_id', new ObjectID); + if ($model->getKeyName() == '_id' and !$model->getKey()) { + $model->setAttribute('_id', new ObjectID()); } // For deeply nested documents, let the parent handle the changes. @@ -63,7 +66,8 @@ public function performInsert(Model $model) /** * Save an existing model and attach it to the parent model. * - * @param \Illuminate\Database\Eloquent\Model $model + * @param \Illuminate\Database\Eloquent\Model $model + * * @return \Illuminate\Database\Eloquent\Model|bool */ public function performUpdate(Model $model) @@ -75,7 +79,7 @@ public function performUpdate(Model $model) } // Use array dot notation for better update behavior. - $values = array_dot($model->getDirty(), $this->localKey . '.'); + $values = array_dot($model->getDirty(), $this->localKey.'.'); $result = $this->getBaseQuery()->update($values); @@ -90,7 +94,8 @@ public function performUpdate(Model $model) /** * Delete an existing model and detach it from the parent model. * - * @param \Illuminate\Database\Eloquent\Model $model + * @param \Illuminate\Database\Eloquent\Model $model + * * @return int */ public function performDelete(Model $model) @@ -116,7 +121,8 @@ public function performDelete(Model $model) /** * Attach the model to its parent. * - * @param \Illuminate\Database\Eloquent\Model $model + * @param \Illuminate\Database\Eloquent\Model $model + * * @return \Illuminate\Database\Eloquent\Model */ public function associate(Model $model) diff --git a/src/Relations/EmbedsOneOrMany.php b/src/Relations/EmbedsOneOrMany.php index d8ce97eab..1fb764bc0 100644 --- a/src/Relations/EmbedsOneOrMany.php +++ b/src/Relations/EmbedsOneOrMany.php @@ -1,4 +1,6 @@ -all(); } - if (! is_array($ids)) { + if (!is_array($ids)) { $ids = [$ids]; } @@ -225,7 +233,8 @@ protected function getEmbedded() /** * Set the embedded records array. * - * @param array $records + * @param array $records + * * @return \Illuminate\Database\Eloquent\Model */ protected function setEmbedded($records) @@ -244,7 +253,8 @@ protected function setEmbedded($records) /** * Get the foreign key value for the relation. * - * @param mixed $id + * @param mixed $id + * * @return mixed */ protected function getForeignKeyValue($id) @@ -260,7 +270,8 @@ protected function getForeignKeyValue($id) /** * Convert an array of records to a Collection. * - * @param array $records + * @param array $records + * * @return \Moloquent\Eloquent\Collection */ protected function toCollection(array $records = []) @@ -281,7 +292,8 @@ protected function toCollection(array $records = []) /** * Create a related model instanced. * - * @param array $attributes + * @param array $attributes + * * @return \Illuminate\Database\Eloquent\Model */ protected function toModel($attributes = []) @@ -349,13 +361,14 @@ protected function isNested() /** * Get the fully qualified local key name. * - * @param string $glue + * @param string $glue + * * @return string */ protected function getPathHierarchy($glue = '.') { if ($parentRelation = $this->getParentRelation()) { - return $parentRelation->getPathHierarchy($glue) . $glue . $this->localKey; + return $parentRelation->getPathHierarchy($glue).$glue.$this->localKey; } return $this->localKey; @@ -369,7 +382,7 @@ protected function getPathHierarchy($glue = '.') public function getQualifiedParentKeyName() { if ($parentRelation = $this->getParentRelation()) { - return $parentRelation->getPathHierarchy() . '.' . $this->parent->getKeyName(); + return $parentRelation->getPathHierarchy().'.'.$this->parent->getKeyName(); } return $this->parent->getKeyName(); diff --git a/src/Relations/HasMany.php b/src/Relations/HasMany.php index 25cee6730..8f74c3aa6 100644 --- a/src/Relations/HasMany.php +++ b/src/Relations/HasMany.php @@ -1,4 +1,6 @@ -getAttribute($key) : $model->getKey(); - + if ($this->related->useMongoId()) { $model->setRelationCast($key); @@ -37,7 +39,8 @@ protected function getKeys(array $models, $key = null) /** * Build model dictionary keyed by the relation's foreign key. * - * @param \Illuminate\Database\Eloquent\Collection $results + * @param \Illuminate\Database\Eloquent\Collection $results + * * @return array */ protected function buildDictionary(Collection $results) @@ -50,6 +53,7 @@ protected function buildDictionary(Collection $results) foreach ($results as $result) { $dictionary[(string) $result->{$foreign}][] = $result; } + return $dictionary; } @@ -66,6 +70,7 @@ public function getParentKey() && $this->related->hasCast($this->localKey, null, 'set')) { $id = $this->related->castAttribute($this->localKey, $id, 'set'); } + return $id; } } diff --git a/src/Relations/MorphMany.php b/src/Relations/MorphMany.php index b21625b89..39fbef3b0 100644 --- a/src/Relations/MorphMany.php +++ b/src/Relations/MorphMany.php @@ -1,4 +1,6 @@ - 'London']); $address->setEventDispatcher($events = Mockery::mock('Illuminate\Events\Dispatcher')); - $events->shouldReceive('until')->once()->with('eloquent.saving: ' . get_class($address), $address)->andReturn(true); - $events->shouldReceive('until')->once()->with('eloquent.creating: ' . get_class($address), $address)->andReturn(true); - $events->shouldReceive('fire')->once()->with('eloquent.created: ' . get_class($address), $address); - $events->shouldReceive('fire')->once()->with('eloquent.saved: ' . get_class($address), $address); + $events->shouldReceive('until')->once()->with('eloquent.saving: '.get_class($address), $address)->andReturn(true); + $events->shouldReceive('until')->once()->with('eloquent.creating: '.get_class($address), $address)->andReturn(true); + $events->shouldReceive('fire')->once()->with('eloquent.created: '.get_class($address), $address); + $events->shouldReceive('fire')->once()->with('eloquent.saved: '.get_class($address), $address); $address = $user->addresses()->save($address); $address->unsetEventDispatcher(); @@ -46,10 +46,10 @@ public function testEmbedsManySave() $this->assertEquals(['London', 'Paris'], $user->addresses->pluck('city')->all()); $address->setEventDispatcher($events = Mockery::mock('Illuminate\Events\Dispatcher')); - $events->shouldReceive('until')->once()->with('eloquent.saving: ' . get_class($address), $address)->andReturn(true); - $events->shouldReceive('until')->once()->with('eloquent.updating: ' . get_class($address), $address)->andReturn(true); - $events->shouldReceive('fire')->once()->with('eloquent.updated: ' . get_class($address), $address); - $events->shouldReceive('fire')->once()->with('eloquent.saved: ' . get_class($address), $address); + $events->shouldReceive('until')->once()->with('eloquent.saving: '.get_class($address), $address)->andReturn(true); + $events->shouldReceive('until')->once()->with('eloquent.updating: '.get_class($address), $address)->andReturn(true); + $events->shouldReceive('fire')->once()->with('eloquent.updated: '.get_class($address), $address); + $events->shouldReceive('fire')->once()->with('eloquent.saved: '.get_class($address), $address); $address->city = 'New York'; $user->addresses()->save($address); @@ -76,7 +76,7 @@ public function testEmbedsManySave() $this->assertEquals(['London', 'New York', 'Bruxelles'], $user->addresses->pluck('city')->all()); $address = $user->addresses[1]; - $address->city = "Manhattan"; + $address->city = 'Manhattan'; $user->addresses()->save($address); $this->assertEquals(['London', 'Manhattan', 'Bruxelles'], $user->addresses->pluck('city')->all()); @@ -211,8 +211,8 @@ public function testEmbedsManyDestroy() $address = $user->addresses->first(); $address->setEventDispatcher($events = Mockery::mock('Illuminate\Events\Dispatcher')); - $events->shouldReceive('until')->once()->with('eloquent.deleting: ' . get_class($address), Mockery::type('Address'))->andReturn(true); - $events->shouldReceive('fire')->once()->with('eloquent.deleted: ' . get_class($address), Mockery::type('Address')); + $events->shouldReceive('until')->once()->with('eloquent.deleting: '.get_class($address), Mockery::type('Address'))->andReturn(true); + $events->shouldReceive('fire')->once()->with('eloquent.deleted: '.get_class($address), Mockery::type('Address')); $user->addresses()->destroy($address->_id); $this->assertEquals(['Bristol', 'Bruxelles'], $user->addresses->pluck('city')->all()); @@ -249,8 +249,8 @@ public function testEmbedsManyDelete() $address = $user->addresses->first(); $address->setEventDispatcher($events = Mockery::mock('Illuminate\Events\Dispatcher')); - $events->shouldReceive('until')->once()->with('eloquent.deleting: ' . get_class($address), Mockery::type('Address'))->andReturn(true); - $events->shouldReceive('fire')->once()->with('eloquent.deleted: ' . get_class($address), Mockery::type('Address')); + $events->shouldReceive('until')->once()->with('eloquent.deleting: '.get_class($address), Mockery::type('Address'))->andReturn(true); + $events->shouldReceive('fire')->once()->with('eloquent.deleted: '.get_class($address), Mockery::type('Address')); $address->delete(); @@ -297,8 +297,8 @@ public function testEmbedsManyCreatingEventReturnsFalse() $address = new Address(['city' => 'London']); $address->setEventDispatcher($events = Mockery::mock('Illuminate\Events\Dispatcher')); - $events->shouldReceive('until')->once()->with('eloquent.saving: ' . get_class($address), $address)->andReturn(true); - $events->shouldReceive('until')->once()->with('eloquent.creating: ' . get_class($address), $address)->andReturn(false); + $events->shouldReceive('until')->once()->with('eloquent.saving: '.get_class($address), $address)->andReturn(true); + $events->shouldReceive('until')->once()->with('eloquent.creating: '.get_class($address), $address)->andReturn(false); $this->assertFalse($user->addresses()->save($address)); $address->unsetEventDispatcher(); @@ -311,7 +311,7 @@ public function testEmbedsManySavingEventReturnsFalse() $address->exists = true; $address->setEventDispatcher($events = Mockery::mock('Illuminate\Events\Dispatcher')); - $events->shouldReceive('until')->once()->with('eloquent.saving: ' . get_class($address), $address)->andReturn(false); + $events->shouldReceive('until')->once()->with('eloquent.saving: '.get_class($address), $address)->andReturn(false); $this->assertFalse($user->addresses()->save($address)); $address->unsetEventDispatcher(); @@ -324,8 +324,8 @@ public function testEmbedsManyUpdatingEventReturnsFalse() $user->addresses()->save($address); $address->setEventDispatcher($events = Mockery::mock('Illuminate\Events\Dispatcher')); - $events->shouldReceive('until')->once()->with('eloquent.saving: ' . get_class($address), $address)->andReturn(true); - $events->shouldReceive('until')->once()->with('eloquent.updating: ' . get_class($address), $address)->andReturn(false); + $events->shouldReceive('until')->once()->with('eloquent.saving: '.get_class($address), $address)->andReturn(true); + $events->shouldReceive('until')->once()->with('eloquent.updating: '.get_class($address), $address)->andReturn(false); $address->city = 'Warsaw'; @@ -341,7 +341,7 @@ public function testEmbedsManyDeletingEventReturnsFalse() $address = $user->addresses->first(); $address->setEventDispatcher($events = Mockery::mock('Illuminate\Events\Dispatcher')); - $events->shouldReceive('until')->once()->with('eloquent.deleting: ' . get_class($address), Mockery::mustBe($address))->andReturn(false); + $events->shouldReceive('until')->once()->with('eloquent.deleting: '.get_class($address), Mockery::mustBe($address))->andReturn(false); $this->assertEquals(0, $user->addresses()->destroy($address)); $this->assertEquals(['New York'], $user->addresses->pluck('city')->all()); @@ -444,10 +444,10 @@ public function testEmbedsOne() $father = new User(['name' => 'Mark Doe']); $father->setEventDispatcher($events = Mockery::mock('Illuminate\Events\Dispatcher')); - $events->shouldReceive('until')->once()->with('eloquent.saving: ' . get_class($father), $father)->andReturn(true); - $events->shouldReceive('until')->once()->with('eloquent.creating: ' . get_class($father), $father)->andReturn(true); - $events->shouldReceive('fire')->once()->with('eloquent.created: ' . get_class($father), $father); - $events->shouldReceive('fire')->once()->with('eloquent.saved: ' . get_class($father), $father); + $events->shouldReceive('until')->once()->with('eloquent.saving: '.get_class($father), $father)->andReturn(true); + $events->shouldReceive('until')->once()->with('eloquent.creating: '.get_class($father), $father)->andReturn(true); + $events->shouldReceive('fire')->once()->with('eloquent.created: '.get_class($father), $father); + $events->shouldReceive('fire')->once()->with('eloquent.saved: '.get_class($father), $father); $father = $user->father()->save($father); $father->unsetEventDispatcher(); @@ -463,10 +463,10 @@ public function testEmbedsOne() $this->assertInstanceOf('MongoDB\BSON\ObjectID', $raw['_id']); $father->setEventDispatcher($events = Mockery::mock('Illuminate\Events\Dispatcher')); - $events->shouldReceive('until')->once()->with('eloquent.saving: ' . get_class($father), $father)->andReturn(true); - $events->shouldReceive('until')->once()->with('eloquent.updating: ' . get_class($father), $father)->andReturn(true); - $events->shouldReceive('fire')->once()->with('eloquent.updated: ' . get_class($father), $father); - $events->shouldReceive('fire')->once()->with('eloquent.saved: ' . get_class($father), $father); + $events->shouldReceive('until')->once()->with('eloquent.saving: '.get_class($father), $father)->andReturn(true); + $events->shouldReceive('until')->once()->with('eloquent.updating: '.get_class($father), $father)->andReturn(true); + $events->shouldReceive('fire')->once()->with('eloquent.updated: '.get_class($father), $father); + $events->shouldReceive('fire')->once()->with('eloquent.saved: '.get_class($father), $father); $father->name = 'Tom Doe'; $user->father()->save($father); @@ -478,10 +478,10 @@ public function testEmbedsOne() $father = new User(['name' => 'Jim Doe']); $father->setEventDispatcher($events = Mockery::mock('Illuminate\Events\Dispatcher')); - $events->shouldReceive('until')->once()->with('eloquent.saving: ' . get_class($father), $father)->andReturn(true); - $events->shouldReceive('until')->once()->with('eloquent.creating: ' . get_class($father), $father)->andReturn(true); - $events->shouldReceive('fire')->once()->with('eloquent.created: ' . get_class($father), $father); - $events->shouldReceive('fire')->once()->with('eloquent.saved: ' . get_class($father), $father); + $events->shouldReceive('until')->once()->with('eloquent.saving: '.get_class($father), $father)->andReturn(true); + $events->shouldReceive('until')->once()->with('eloquent.creating: '.get_class($father), $father)->andReturn(true); + $events->shouldReceive('fire')->once()->with('eloquent.created: '.get_class($father), $father); + $events->shouldReceive('fire')->once()->with('eloquent.saved: '.get_class($father), $father); $father = $user->father()->save($father); $father->unsetEventDispatcher(); @@ -496,7 +496,7 @@ public function testEmbedsOneAssociate() $father = new User(['name' => 'Mark Doe']); $father->setEventDispatcher($events = Mockery::mock('Illuminate\Events\Dispatcher')); - $events->shouldReceive('until')->times(0)->with('eloquent.saving: ' . get_class($father), $father); + $events->shouldReceive('until')->times(0)->with('eloquent.saving: '.get_class($father), $father); $father = $user->father()->associate($father); $father->unsetEventDispatcher(); @@ -664,7 +664,7 @@ public function testDoubleAssociate() public function testSaveEmptyModel() { $user = User::create(['name' => 'John Doe']); - $user->addresses()->save(new Address); + $user->addresses()->save(new Address()); $this->assertNotNull($user->addresses); $this->assertEquals(1, $user->addresses()->count()); } diff --git a/tests/ModelTest.php b/tests/ModelTest.php index e9f6bf306..8c36bdb75 100644 --- a/tests/ModelTest.php +++ b/tests/ModelTest.php @@ -12,7 +12,7 @@ public function tearDown() public function testNewModel() { - $user = new User; + $user = new User(); $this->assertInstanceOf('Moloquent\Eloquent\Model', $user); $this->assertInstanceOf('Moloquent\Connection', $user->getConnection()); $this->assertEquals(false, $user->exists); @@ -22,7 +22,7 @@ public function testNewModel() public function testInsert() { - $user = new User; + $user = new User(); $user->name = 'John Doe'; $user->title = 'admin'; $user->age = 35; @@ -47,7 +47,7 @@ public function testInsert() public function testUpdate() { - $user = new User; + $user = new User(); $user->name = 'John Doe'; $user->title = 'admin'; $user->age = 35; @@ -80,7 +80,7 @@ public function testUpdate() public function testManualStringId() { - $user = new User; + $user = new User(); $user->_id = '4af9f23d8ead0e1d32000000'; $user->name = 'John Doe'; $user->title = 'admin'; @@ -93,7 +93,7 @@ public function testManualStringId() $raw = $user->getAttributes(); $this->assertInstanceOf('MongoDB\BSON\ObjectID', $raw['_id']); - $user = new User; + $user = new User(); $user->_id = 'customId'; $user->name = 'John Doe'; $user->title = 'admin'; @@ -109,7 +109,7 @@ public function testManualStringId() public function testManualIntId() { - $user = new User; + $user = new User(); $user->_id = 1; $user->name = 'John Doe'; $user->title = 'admin'; @@ -125,7 +125,7 @@ public function testManualIntId() public function testDelete() { - $user = new User; + $user = new User(); $user->name = 'John Doe'; $user->title = 'admin'; $user->age = 35; @@ -141,13 +141,13 @@ public function testDelete() public function testAll() { - $user = new User; + $user = new User(); $user->name = 'John Doe'; $user->title = 'admin'; $user->age = 35; $user->save(); - $user = new User; + $user = new User(); $user->name = 'Jane Doe'; $user->title = 'user'; $user->age = 32; @@ -162,7 +162,7 @@ public function testAll() public function testFind() { - $user = new User; + $user = new User(); $user->name = 'John Doe'; $user->title = 'admin'; $user->age = 35; @@ -236,7 +236,7 @@ public function testCreate() public function testDestroy() { - $user = new User; + $user = new User(); $user->name = 'John Doe'; $user->title = 'admin'; $user->age = 35; @@ -249,7 +249,7 @@ public function testDestroy() public function testTouch() { - $user = new User; + $user = new User(); $user->name = 'John Doe'; $user->title = 'admin'; $user->age = 35; @@ -297,10 +297,10 @@ public function testSoftDelete() public function testPrimaryKey() { - $user = new User; + $user = new User(); $this->assertEquals('_id', $user->getKeyName()); - $book = new Book; + $book = new Book(); $this->assertEquals('title', $book->getKeyName()); $book->title = 'A Game of Thrones'; @@ -401,7 +401,7 @@ public function testDates() $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); + $user->setAttribute('entry.date', new DateTime()); $this->assertInstanceOf('Carbon\Carbon', $user->getAttribute('entry.date')); $data = $user->toArray(); diff --git a/tests/MysqlRelationsTest.php b/tests/MysqlRelationsTest.php index 6dbd0571f..aa1313d70 100644 --- a/tests/MysqlRelationsTest.php +++ b/tests/MysqlRelationsTest.php @@ -20,12 +20,12 @@ public function tearDown() public function testMysqlRelations() { - $user = new MysqlUser; + $user = new MysqlUser(); $this->assertInstanceOf('MysqlUser', $user); $this->assertInstanceOf('Illuminate\Database\MySqlConnection', $user->getConnection()); // Mysql User - $user->name = "John Doe"; + $user->name = 'John Doe'; $user->save(); $this->assertTrue(is_int($user->id)); @@ -50,8 +50,8 @@ public function testMysqlRelations() $this->assertEquals('John Doe', $role->mysqlUser->name); // MongoDB User - $user = new User; - $user->name = "John Doe"; + $user = new User(); + $user->name = 'John Doe'; $user->save(); // MongoDB has many diff --git a/tests/QueryBuilderTest.php b/tests/QueryBuilderTest.php index 81d9ca93b..1aff0893e 100644 --- a/tests/QueryBuilderTest.php +++ b/tests/QueryBuilderTest.php @@ -1,7 +1,7 @@ insert([ - ['name' => 'knife', 'amount' => [['hidden' => 10, 'found' => 3],['hidden' => 5, 'found' => 2]]], - ['name' => 'fork', 'amount' => [['hidden' => 35, 'found' => 12],['hidden' => 7, 'found' => 17],['hidden' => 1, 'found' => 19]]], + ['name' => 'knife', 'amount' => [['hidden' => 10, 'found' => 3], ['hidden' => 5, 'found' => 2]]], + ['name' => 'fork', 'amount' => [['hidden' => 35, 'found' => 12], ['hidden' => 7, 'found' => 17], ['hidden' => 1, 'found' => 19]]], ['name' => 'spoon', 'amount' => [['hidden' => 14, 'found' => 21]]], ['name' => 'teaspoon', 'amount' => []], ]); @@ -489,20 +489,20 @@ public function testUpdateSubdocument() public function testDates() { DB::collection('users')->insert([ - ['name' => 'John Doe', 'birthday' => new UTCDateTime(1000 * strtotime("1980-01-01 00:00:00"))], - ['name' => 'Jane Doe', 'birthday' => new UTCDateTime(1000 * strtotime("1981-01-01 00:00:00"))], - ['name' => 'Robert Roe', 'birthday' => new UTCDateTime(1000 * strtotime("1982-01-01 00:00:00"))], - ['name' => 'Mark Moe', 'birthday' => new UTCDateTime(1000 * strtotime("1983-01-01 00:00:00"))], + ['name' => 'John Doe', 'birthday' => new UTCDateTime(1000 * strtotime('1980-01-01 00:00:00'))], + ['name' => 'Jane Doe', 'birthday' => new UTCDateTime(1000 * strtotime('1981-01-01 00:00:00'))], + ['name' => 'Robert Roe', 'birthday' => new UTCDateTime(1000 * strtotime('1982-01-01 00:00:00'))], + ['name' => 'Mark Moe', 'birthday' => new UTCDateTime(1000 * strtotime('1983-01-01 00:00:00'))], ]); - $user = DB::collection('users')->where('birthday', new UTCDateTime(1000 * strtotime("1980-01-01 00:00:00")))->first(); + $user = DB::collection('users')->where('birthday', new UTCDateTime(1000 * 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(); + $user = DB::collection('users')->where('birthday', '=', new DateTime('1980-01-01 00:00:00'))->first(); $this->assertEquals('John Doe', $user['name']); - $start = new UTCDateTime(1000 * strtotime("1981-01-01 00:00:00")); - $stop = new UTCDateTime(1000 * strtotime("1982-01-01 00:00:00")); + $start = new UTCDateTime(1000 * strtotime('1981-01-01 00:00:00')); + $stop = new UTCDateTime(1000 * strtotime('1982-01-01 00:00:00')); $users = DB::collection('users')->whereBetween('birthday', [$start, $stop])->get(); $this->assertEquals(2, count($users)); @@ -565,11 +565,11 @@ public function testOperators() $results = DB::collection('items')->where('tags', 'size', 4)->get(); $this->assertEquals(1, count($results)); - $regex = new Regex(".*doe", "i"); + $regex = new Regex('.*doe', 'i'); $results = DB::collection('users')->where('name', 'regex', $regex)->get(); $this->assertEquals(2, count($results)); - $regex = new Regex(".*doe", "i"); + $regex = new Regex('.*doe', 'i'); $results = DB::collection('users')->where('name', 'regexp', $regex)->get(); $this->assertEquals(2, count($results)); diff --git a/tests/RelationsWithMongoIdTest.php b/tests/RelationsWithMongoIdTest.php index 294d45ff4..b84d9792d 100644 --- a/tests/RelationsWithMongoIdTest.php +++ b/tests/RelationsWithMongoIdTest.php @@ -527,15 +527,15 @@ public function testDoubleSaveManyToMany() public function testCastAttribute() { - $user = new User; + $user = new User(); $user->setCasts([ 'last_seen' => 'UTCDatetime', - 'age' => 'int', - 'name' => 'string', - 'rate' => 'float', - 'birthday' => 'timestamp', - 'isActive' => 'bool', - 'default' => 'default', + 'age' => 'int', + 'name' => 'string', + 'rate' => 'float', + 'birthday' => 'timestamp', + 'isActive' => 'bool', + 'default' => 'default', ], 'set'); $user->setCasts([ 'name' => 'string', diff --git a/tests/SchemaTest.php b/tests/SchemaTest.php index df51af09f..bb81ab8c3 100644 --- a/tests/SchemaTest.php +++ b/tests/SchemaTest.php @@ -178,7 +178,7 @@ public function testDummies() public function testSparseUnique() { Schema::collection('newcollection', function ($collection) { - $collection->sparse_and_unique('sparseuniquekey'); + $collection->sparse_and_unique('sparseuniquekey'); }); $index = $this->getIndex('newcollection', 'sparseuniquekey'); diff --git a/tests/SeederTest.php b/tests/SeederTest.php index 9581df3d3..934c892a2 100644 --- a/tests/SeederTest.php +++ b/tests/SeederTest.php @@ -9,7 +9,7 @@ public function tearDown() public function testSeed() { - $seeder = new UserTableSeeder; + $seeder = new UserTableSeeder(); $seeder->run(); $user = User::where('name', 'John Doe')->first(); diff --git a/tests/TestCase.php b/tests/TestCase.php index 7833d8626..9b0e4671f 100644 --- a/tests/TestCase.php +++ b/tests/TestCase.php @@ -5,7 +5,7 @@ class TestCase extends Orchestra\Testbench\TestCase /** * Get application providers. * - * @param \Illuminate\Foundation\Application $app + * @param \Illuminate\Foundation\Application $app * * @return array */ @@ -21,7 +21,8 @@ protected function getApplicationProviders($app) /** * Get package providers. * - * @param \Illuminate\Foundation\Application $app + * @param \Illuminate\Foundation\Application $app + * * @return array */ protected function getPackageProviders($app) @@ -35,7 +36,8 @@ protected function getPackageProviders($app) /** * Define environment setup. * - * @param Illuminate\Foundation\Application $app + * @param Illuminate\Foundation\Application $app + * * @return void */ protected function getEnvironmentSetUp($app) diff --git a/tests/models/Book.php b/tests/models/Book.php index 01dc63e6c..d5fae3090 100644 --- a/tests/models/Book.php +++ b/tests/models/Book.php @@ -1,7 +1,6 @@ Date: Sun, 11 Sep 2016 13:34:35 +0430 Subject: [PATCH 39/88] Disable Travis Notifications --- .travis.yml | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index 3e93fe2ab..65b320c15 100644 --- a/.travis.yml +++ b/.travis.yml @@ -31,4 +31,7 @@ script: - vendor/bin/phpunit --coverage-clover build/logs/clover.xml after_success: - - sh -c 'php vendor/bin/coveralls -v' + - sh -c 'php vendor/bin/coveralls -v' + +notifications: + - email: false From 3473f72d858892a36fd73771ddc8b84ebfe328a3 Mon Sep 17 00:00:00 2001 From: hooman naghiee Date: Sun, 11 Sep 2016 15:10:51 +0430 Subject: [PATCH 40/88] add SupportClasses for Jenssegers\Mongodb\Eloquent\Model --- composer.json | 5 ++++- src/Moloquent/SupportClasses/JenssegersModel.php | 8 ++++++++ 2 files changed, 12 insertions(+), 1 deletion(-) create mode 100644 src/Moloquent/SupportClasses/JenssegersModel.php diff --git a/composer.json b/composer.json index be710f474..c99dbcac1 100644 --- a/composer.json +++ b/composer.json @@ -38,7 +38,10 @@ "autoload": { "psr-0" :{ "Moloquent\\": "src/" - } + }, + "files" : [ + "src/Moloquent/SupportClasses/JenssegersModel.php" + ] }, "autoload-dev": { "classmap": [ diff --git a/src/Moloquent/SupportClasses/JenssegersModel.php b/src/Moloquent/SupportClasses/JenssegersModel.php new file mode 100644 index 000000000..29aaf3760 --- /dev/null +++ b/src/Moloquent/SupportClasses/JenssegersModel.php @@ -0,0 +1,8 @@ + Date: Sun, 11 Sep 2016 15:12:55 +0430 Subject: [PATCH 41/88] cs fix --- src/Moloquent/SupportClasses/JenssegersModel.php | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/Moloquent/SupportClasses/JenssegersModel.php b/src/Moloquent/SupportClasses/JenssegersModel.php index 29aaf3760..10c71a787 100644 --- a/src/Moloquent/SupportClasses/JenssegersModel.php +++ b/src/Moloquent/SupportClasses/JenssegersModel.php @@ -1,8 +1,9 @@ Date: Sun, 11 Sep 2016 15:28:36 +0430 Subject: [PATCH 42/88] add Support.php file to check if the class exists --- composer.json | 2 +- src/Moloquent/SupportClasses/JenssegersModel.php | 2 +- src/Moloquent/SupportClasses/Support.php | 4 ++++ 3 files changed, 6 insertions(+), 2 deletions(-) create mode 100644 src/Moloquent/SupportClasses/Support.php diff --git a/composer.json b/composer.json index c99dbcac1..57cbc0342 100644 --- a/composer.json +++ b/composer.json @@ -40,7 +40,7 @@ "Moloquent\\": "src/" }, "files" : [ - "src/Moloquent/SupportClasses/JenssegersModel.php" + "src/Moloquent/SupportClasses/Support.php" ] }, "autoload-dev": { diff --git a/src/Moloquent/SupportClasses/JenssegersModel.php b/src/Moloquent/SupportClasses/JenssegersModel.php index 10c71a787..fd4207753 100644 --- a/src/Moloquent/SupportClasses/JenssegersModel.php +++ b/src/Moloquent/SupportClasses/JenssegersModel.php @@ -4,6 +4,6 @@ use Moloquent\Eloquent\Model as MoloquentModel; -class JenssegersModel extends MoloquentModel +class Model extends MoloquentModel { } diff --git a/src/Moloquent/SupportClasses/Support.php b/src/Moloquent/SupportClasses/Support.php new file mode 100644 index 000000000..7cd902a0f --- /dev/null +++ b/src/Moloquent/SupportClasses/Support.php @@ -0,0 +1,4 @@ + Date: Sun, 11 Sep 2016 11:00:29 +0000 Subject: [PATCH 43/88] Applied fixes from StyleCI [ci skip] [skip ci] --- src/Moloquent/SupportClasses/JenssegersModel.php | 2 +- src/Moloquent/SupportClasses/Support.php | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/src/Moloquent/SupportClasses/JenssegersModel.php b/src/Moloquent/SupportClasses/JenssegersModel.php index fd4207753..10c71a787 100644 --- a/src/Moloquent/SupportClasses/JenssegersModel.php +++ b/src/Moloquent/SupportClasses/JenssegersModel.php @@ -4,6 +4,6 @@ use Moloquent\Eloquent\Model as MoloquentModel; -class Model extends MoloquentModel +class JenssegersModel extends MoloquentModel { } diff --git a/src/Moloquent/SupportClasses/Support.php b/src/Moloquent/SupportClasses/Support.php index 7cd902a0f..84bc005e1 100644 --- a/src/Moloquent/SupportClasses/Support.php +++ b/src/Moloquent/SupportClasses/Support.php @@ -1,4 +1,5 @@ Date: Sun, 11 Sep 2016 15:33:28 +0430 Subject: [PATCH 44/88] fix code convention --- .../{JenssegersModel.php => Jenssegers/Model.php} | 0 src/Moloquent/SupportClasses/Support.php | 3 ++- 2 files changed, 2 insertions(+), 1 deletion(-) rename src/Moloquent/SupportClasses/{JenssegersModel.php => Jenssegers/Model.php} (100%) diff --git a/src/Moloquent/SupportClasses/JenssegersModel.php b/src/Moloquent/SupportClasses/Jenssegers/Model.php similarity index 100% rename from src/Moloquent/SupportClasses/JenssegersModel.php rename to src/Moloquent/SupportClasses/Jenssegers/Model.php diff --git a/src/Moloquent/SupportClasses/Support.php b/src/Moloquent/SupportClasses/Support.php index 7cd902a0f..042617fbf 100644 --- a/src/Moloquent/SupportClasses/Support.php +++ b/src/Moloquent/SupportClasses/Support.php @@ -1,4 +1,5 @@ Date: Sun, 11 Sep 2016 15:39:56 +0430 Subject: [PATCH 45/88] Update JenssegersModel.php --- src/Moloquent/SupportClasses/JenssegersModel.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Moloquent/SupportClasses/JenssegersModel.php b/src/Moloquent/SupportClasses/JenssegersModel.php index 10c71a787..fd4207753 100644 --- a/src/Moloquent/SupportClasses/JenssegersModel.php +++ b/src/Moloquent/SupportClasses/JenssegersModel.php @@ -4,6 +4,6 @@ use Moloquent\Eloquent\Model as MoloquentModel; -class JenssegersModel extends MoloquentModel +class Model extends MoloquentModel { } From 6d642e351631eedc322971781ac8de4149859cf4 Mon Sep 17 00:00:00 2001 From: hooman naghiee Date: Sun, 11 Sep 2016 11:10:00 +0000 Subject: [PATCH 46/88] Applied fixes from StyleCI [ci skip] [skip ci] --- src/Moloquent/SupportClasses/JenssegersModel.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Moloquent/SupportClasses/JenssegersModel.php b/src/Moloquent/SupportClasses/JenssegersModel.php index fd4207753..10c71a787 100644 --- a/src/Moloquent/SupportClasses/JenssegersModel.php +++ b/src/Moloquent/SupportClasses/JenssegersModel.php @@ -4,6 +4,6 @@ use Moloquent\Eloquent\Model as MoloquentModel; -class Model extends MoloquentModel +class JenssegersModel extends MoloquentModel { } From ade7ee92809ea5a77b06bff6cb9e41a0b12456f5 Mon Sep 17 00:00:00 2001 From: hooman naghiee Date: Sun, 11 Sep 2016 15:44:22 +0430 Subject: [PATCH 47/88] fix code style and the problem with styleci --- composer.json | 2 +- src/{Moloquent => }/SupportClasses/Jenssegers/Model.php | 2 +- src/{Moloquent => }/SupportClasses/Support.php | 0 3 files changed, 2 insertions(+), 2 deletions(-) rename src/{Moloquent => }/SupportClasses/Jenssegers/Model.php (68%) rename src/{Moloquent => }/SupportClasses/Support.php (100%) diff --git a/composer.json b/composer.json index 1b75c0d72..bbf557e83 100644 --- a/composer.json +++ b/composer.json @@ -40,7 +40,7 @@ "Moloquent\\": "src/" }, "files" : [ - "src/Moloquent/SupportClasses/Support.php" + "src/SupportClasses/Support.php" ] }, "autoload-dev": { diff --git a/src/Moloquent/SupportClasses/Jenssegers/Model.php b/src/SupportClasses/Jenssegers/Model.php similarity index 68% rename from src/Moloquent/SupportClasses/Jenssegers/Model.php rename to src/SupportClasses/Jenssegers/Model.php index 10c71a787..fd4207753 100644 --- a/src/Moloquent/SupportClasses/Jenssegers/Model.php +++ b/src/SupportClasses/Jenssegers/Model.php @@ -4,6 +4,6 @@ use Moloquent\Eloquent\Model as MoloquentModel; -class JenssegersModel extends MoloquentModel +class Model extends MoloquentModel { } diff --git a/src/Moloquent/SupportClasses/Support.php b/src/SupportClasses/Support.php similarity index 100% rename from src/Moloquent/SupportClasses/Support.php rename to src/SupportClasses/Support.php From e53a343e6f575e48baeadcd2751eb6b1a0e9916a Mon Sep 17 00:00:00 2001 From: Ricardo Fontanelli Date: Wed, 14 Sep 2016 16:52:23 -0300 Subject: [PATCH 48/88] Convert whereBetween values to UTCDateTime Added a protected method (dateTimeConvertion) to convert DateTime objects to MongoDB\BSON\UTCDateTime and added a verification for DateTime objects in $where['values'] array to ensure that all DateTime values will be properly converted to MongoDB\BSON\UTCDateTime. --- src/Jenssegers/Mongodb/Query/Builder.php | 27 ++++++++++++++++++++++-- 1 file changed, 25 insertions(+), 2 deletions(-) diff --git a/src/Jenssegers/Mongodb/Query/Builder.php b/src/Jenssegers/Mongodb/Query/Builder.php index 74b9ee3a6..5af7efe1d 100644 --- a/src/Jenssegers/Mongodb/Query/Builder.php +++ b/src/Jenssegers/Mongodb/Query/Builder.php @@ -866,7 +866,16 @@ protected function compileWheres() // Convert DateTime values to UTCDateTime. if (isset($where['value']) and $where['value'] instanceof DateTime) { - $where['value'] = new UTCDateTime($where['value']->getTimestamp() * 1000); + $where['value'] = $this->dateTimeConvertion($where['value']); + } + + // Convert DateTime values to UTCDateTime in $where['values'] key. + if (isset($where['values'])) { + foreach ($where['values'] as $key => $value) { + if ($value instanceof DateTime) { + $where['values'][$key] = $this->dateTimeConvertion($value); + } + } } // The next item in a "chain" of wheres devices the boolean of the @@ -894,7 +903,7 @@ protected function compileWheres() // Merge the compiled where with the others. $compiled = array_merge_recursive($compiled, $result); } - + return $compiled; } @@ -1018,6 +1027,20 @@ protected function compileWhereRaw($where) { return $where['sql']; } + + /** + * Convert to MongoDB\BSON\UTCDateTime if $value is a DateTime object. + * + * @param mixed $value + * @return mixed + */ + protected function dateTimeConvertion($value) + { + if ($value instanceof DateTime) { + return new UTCDateTime($value->getTimestamp() * 1000); + } + return $value; + } /** * Handle dynamic method calls into the method. From 83f7c6322dc28b707ac587b3a176151142b3244c Mon Sep 17 00:00:00 2001 From: Ricardo Fontanelli Date: Wed, 14 Sep 2016 18:16:02 -0300 Subject: [PATCH 49/88] Convert whereBetween values to UTCDateTime Added a protected method (dateTimeConvertion) to convert DateTime objects to MongoDB\BSON\UTCDateTime and added a verification for DateTime objects in $where['values'] array to ensure that all DateTime values will be properly converted to MongoDB\BSON\UTCDateTime. --- src/Jenssegers/Mongodb/Query/Builder.php | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/src/Jenssegers/Mongodb/Query/Builder.php b/src/Jenssegers/Mongodb/Query/Builder.php index 5af7efe1d..1ec8565f3 100644 --- a/src/Jenssegers/Mongodb/Query/Builder.php +++ b/src/Jenssegers/Mongodb/Query/Builder.php @@ -870,10 +870,12 @@ protected function compileWheres() } // Convert DateTime values to UTCDateTime in $where['values'] key. - if (isset($where['values'])) { - foreach ($where['values'] as $key => $value) { - if ($value instanceof DateTime) { - $where['values'][$key] = $this->dateTimeConvertion($value); + if (array_key_exists('values', $where)) { + if (is_array($where['values']) && !empty($where['values'])) { + foreach ($where['values'] as $keyWhere => $valueWhere) { + if ($valueWhere instanceof DateTime) { + $where['values'][$keyWhere] = $this->dateTimeConvertion($valueWhere); + } } } } From 5ad652a0c000d049fcf7952fdc4961f087340b19 Mon Sep 17 00:00:00 2001 From: Ricardo Fontanelli Date: Wed, 14 Sep 2016 18:18:20 -0300 Subject: [PATCH 50/88] CHANGE DateTime object as whereBetween parameter Assert if a MongoDB\BSON\UTCDateTime is created if you set a DateTime object as whereBetween parameter --- tests/QueryBuilderTest.php | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/tests/QueryBuilderTest.php b/tests/QueryBuilderTest.php index ca08bf36a..50acc588c 100644 --- a/tests/QueryBuilderTest.php +++ b/tests/QueryBuilderTest.php @@ -490,6 +490,13 @@ public function testDates() $users = DB::collection('users')->whereBetween('birthday', [$start, $stop])->get(); $this->assertEquals(2, count($users)); + + $dateTimeStart = new DateTime("1981-01-01 00:00:00"); + $dateTimeStop = new DateTime("1982-01-01 00:00:00"); + + $usersWithDateTimeFilter = DB::collection('users')->whereBetween('birthday', [$dateTimeStart, $dateTimeStop])->get(); + $this->assertEquals(2, count($usersWithDateTimeFilter)); + } public function testOperators() From f8e352db8c23ac5d0ddaa1c99b591d8e0cc45269 Mon Sep 17 00:00:00 2001 From: Ricardo Fontanelli Date: Wed, 14 Sep 2016 18:21:28 -0300 Subject: [PATCH 51/88] CHANGE white space CHANGE white space --- tests/QueryBuilderTest.php | 1 - 1 file changed, 1 deletion(-) diff --git a/tests/QueryBuilderTest.php b/tests/QueryBuilderTest.php index 50acc588c..bd843d223 100644 --- a/tests/QueryBuilderTest.php +++ b/tests/QueryBuilderTest.php @@ -496,7 +496,6 @@ public function testDates() $usersWithDateTimeFilter = DB::collection('users')->whereBetween('birthday', [$dateTimeStart, $dateTimeStop])->get(); $this->assertEquals(2, count($usersWithDateTimeFilter)); - } public function testOperators() From 8c11aa830af99b531179b230be4fc222d1dda08d Mon Sep 17 00:00:00 2001 From: Pooya Parsa Date: Thu, 15 Sep 2016 09:45:33 +0000 Subject: [PATCH 52/88] Applied fixes from StyleCI [ci skip] [skip ci] --- src/Query/Builder.php | 8 +++++--- tests/QueryBuilderTest.php | 4 ++-- 2 files changed, 7 insertions(+), 5 deletions(-) diff --git a/src/Query/Builder.php b/src/Query/Builder.php index 0ed6765e9..b90013dd3 100644 --- a/src/Query/Builder.php +++ b/src/Query/Builder.php @@ -965,7 +965,7 @@ protected function compileWheres() // Merge the compiled where with the others. $compiled = array_merge_recursive($compiled, $result); } - + return $compiled; } @@ -1089,11 +1089,12 @@ protected function compileWhereRaw($where) { return $where['sql']; } - + /** * Convert to MongoDB\BSON\UTCDateTime if $value is a DateTime object. * - * @param mixed $value + * @param mixed $value + * * @return mixed */ protected function dateTimeConvertion($value) @@ -1101,6 +1102,7 @@ protected function dateTimeConvertion($value) if ($value instanceof DateTime) { return new UTCDateTime($value->getTimestamp() * 1000); } + return $value; } diff --git a/tests/QueryBuilderTest.php b/tests/QueryBuilderTest.php index 29ea85b7c..c449f27bb 100644 --- a/tests/QueryBuilderTest.php +++ b/tests/QueryBuilderTest.php @@ -507,8 +507,8 @@ public function testDates() $users = DB::collection('users')->whereBetween('birthday', [$start, $stop])->get(); $this->assertEquals(2, count($users)); - $dateTimeStart = new DateTime("1981-01-01 00:00:00"); - $dateTimeStop = new DateTime("1982-01-01 00:00:00"); + $dateTimeStart = new DateTime('1981-01-01 00:00:00'); + $dateTimeStop = new DateTime('1982-01-01 00:00:00'); $usersWithDateTimeFilter = DB::collection('users')->whereBetween('birthday', [$dateTimeStart, $dateTimeStop])->get(); $this->assertEquals(2, count($usersWithDateTimeFilter)); From 19a71838303e983ccfaa0f86439c81fea06bf72d Mon Sep 17 00:00:00 2001 From: Ryan Hayle Date: Mon, 19 Sep 2016 13:00:37 -0500 Subject: [PATCH 53/88] Allow setting custom options on a query [Fixes #541] --- src/Jenssegers/Mongodb/Query/Builder.php | 30 ++++++++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/src/Jenssegers/Mongodb/Query/Builder.php b/src/Jenssegers/Mongodb/Query/Builder.php index 74b9ee3a6..9e0dad023 100644 --- a/src/Jenssegers/Mongodb/Query/Builder.php +++ b/src/Jenssegers/Mongodb/Query/Builder.php @@ -41,6 +41,13 @@ class Builder extends BaseBuilder */ public $hint; + /** + * Custom options to add to the query. + * + * @var array + */ + public $options = []; + /** * Indicate if we are executing a pagination query. * @@ -263,6 +270,11 @@ public function getFresh($columns = []) 'typeMap' => ['root' => 'array', 'document' => 'array'], ]; + // Add custom query options + if (count($this->options)) { + $options = array_merge($options, $this->options); + } + // Execute aggregation $results = iterator_to_array($this->collection->aggregate($pipeline, $options)); @@ -321,6 +333,11 @@ public function getFresh($columns = []) // Fix for legacy support, converts the results to arrays instead of objects. $options['typeMap'] = ['root' => 'array', 'document' => 'array']; + // Add custom query options + if (count($this->options)) { + $options = array_merge($options, $this->options); + } + // Execute query and get MongoCursor $cursor = $this->collection->find($wheres, $options); @@ -1019,6 +1036,19 @@ protected function compileWhereRaw($where) return $where['sql']; } + /** + * Set custom options for the query. + * + * @param array $options + * @return $this + */ + public function options(array $options) + { + $this->options = $options; + + return $this; + } + /** * Handle dynamic method calls into the method. * From c1ba38f2ed78f9941193ba95613d39893ddc3a9e Mon Sep 17 00:00:00 2001 From: pi0 Date: Fri, 23 Sep 2016 12:12:32 +0330 Subject: [PATCH 54/88] Moloquent Native Authenticatable User Class --- src/Auth/User.php | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 src/Auth/User.php diff --git a/src/Auth/User.php b/src/Auth/User.php new file mode 100644 index 000000000..42711ee96 --- /dev/null +++ b/src/Auth/User.php @@ -0,0 +1,19 @@ + Date: Fri, 23 Sep 2016 12:21:14 +0330 Subject: [PATCH 55/88] use Authenticatable for tests Model --- tests/models/User.php | 11 ++++------- 1 file changed, 4 insertions(+), 7 deletions(-) diff --git a/tests/models/User.php b/tests/models/User.php index 97981ac3c..44fdfcd83 100644 --- a/tests/models/User.php +++ b/tests/models/User.php @@ -1,14 +1,11 @@ Date: Fri, 23 Sep 2016 13:31:41 +0330 Subject: [PATCH 56/88] Passport Support --- composer.json | 1 + phpunit.xml.dist | 3 + src/Passport/Client.php | 74 ++++++++++++++++++++++++ src/Passport/PassportServiceProvider.php | 19 ++++++ src/Passport/PersonalAccessClient.php | 32 ++++++++++ tests/PassportTest.php | 26 +++++++++ tests/TestCase.php | 2 + 7 files changed, 157 insertions(+) create mode 100644 src/Passport/Client.php create mode 100644 src/Passport/PassportServiceProvider.php create mode 100644 src/Passport/PersonalAccessClient.php create mode 100644 tests/PassportTest.php diff --git a/composer.json b/composer.json index bbf557e83..201a8def0 100644 --- a/composer.json +++ b/composer.json @@ -30,6 +30,7 @@ "mongodb/mongodb": "^1.0.0" }, "require-dev": { + "laravel/passport": "^1.0", "phpunit/phpunit": "^4.0|^5.0", "orchestra/testbench": "^3.1", "mockery/mockery": "^0.9", diff --git a/phpunit.xml.dist b/phpunit.xml.dist index cf7703c88..14c440728 100644 --- a/phpunit.xml.dist +++ b/phpunit.xml.dist @@ -45,6 +45,9 @@ tests/ValidationTest.php + + tests/PassportTest.php + diff --git a/src/Passport/Client.php b/src/Passport/Client.php new file mode 100644 index 000000000..037636472 --- /dev/null +++ b/src/Passport/Client.php @@ -0,0 +1,74 @@ + 'bool', + 'password_client' => 'bool', + 'revoked' => 'bool', + ]; + + /** + * Get all of the authentication codes for the client. + * + * @return \Illuminate\Database\Eloquent\Relations\HasMany + */ + public function authCodes() + { + return $this->hasMany(AuthCode::class); + } + + /** + * Get all of the tokens that belong to the client. + * + * @return \Illuminate\Database\Eloquent\Relations\HasMany + */ + public function tokens() + { + return $this->hasMany(Token::class); + } + + /** + * Determine if the client is a "first party" client. + * + * @return bool + */ + public function firstParty() + { + return $this->personal_access_client || $this->password_client; + } +} diff --git a/src/Passport/PassportServiceProvider.php b/src/Passport/PassportServiceProvider.php new file mode 100644 index 000000000..be2f2eaff --- /dev/null +++ b/src/Passport/PassportServiceProvider.php @@ -0,0 +1,19 @@ +alias('Laravel\Passport\Client', Client::class); + $loader->alias('Laravel\Passport\PersonalAccessClient', PersonalAccessClient::class); + } + +} diff --git a/src/Passport/PersonalAccessClient.php b/src/Passport/PersonalAccessClient.php new file mode 100644 index 000000000..c68cdbd40 --- /dev/null +++ b/src/Passport/PersonalAccessClient.php @@ -0,0 +1,32 @@ +belongsTo(Client::class); + } +} diff --git a/tests/PassportTest.php b/tests/PassportTest.php new file mode 100644 index 000000000..fa2d63b11 --- /dev/null +++ b/tests/PassportTest.php @@ -0,0 +1,26 @@ +delete(); + DB::collection('oauth_access_tokens')->delete(); + DB::collection('oauth_clients')->delete(); + DB::collection('oauth_personal_access_clients')->delete(); + DB::collection('oauth_refresh_tokens')->delete(); + } + + public function testPassportInstall() + { + $result=Artisan::call('passport:install',[]); + $this->assertEquals(0,$result); + } + +} diff --git a/tests/TestCase.php b/tests/TestCase.php index 9b0e4671f..25819b6c0 100644 --- a/tests/TestCase.php +++ b/tests/TestCase.php @@ -30,6 +30,8 @@ protected function getPackageProviders($app) return [ Moloquent\MongodbServiceProvider::class, Moloquent\Auth\PasswordResetServiceProvider::class, + Moloquent\Passport\PassportServiceProvider::class, + Laravel\Passport\PassportServiceProvider::class, ]; } From 10d237279fb38e7e82067b27aa338dc2d7b05b06 Mon Sep 17 00:00:00 2001 From: Pooya Parsa Date: Fri, 23 Sep 2016 10:01:56 +0000 Subject: [PATCH 57/88] Applied fixes from StyleCI [ci skip] [skip ci] --- src/Auth/User.php | 6 +++--- src/Passport/Client.php | 4 ++-- src/Passport/PassportServiceProvider.php | 1 - tests/PassportTest.php | 6 ++---- 4 files changed, 7 insertions(+), 10 deletions(-) diff --git a/src/Auth/User.php b/src/Auth/User.php index 42711ee96..d42215514 100644 --- a/src/Auth/User.php +++ b/src/Auth/User.php @@ -3,12 +3,12 @@ namespace Moloquent\Auth; use Illuminate\Auth\Authenticatable; -use Moloquent\Eloquent\Model; use Illuminate\Auth\Passwords\CanResetPassword; -use Illuminate\Foundation\Auth\Access\Authorizable; -use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract; use Illuminate\Contracts\Auth\Access\Authorizable as AuthorizableContract; +use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract; use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract; +use Illuminate\Foundation\Auth\Access\Authorizable; +use Moloquent\Eloquent\Model; class User extends Model implements AuthenticatableContract, diff --git a/src/Passport/Client.php b/src/Passport/Client.php index 037636472..9ca3bb730 100644 --- a/src/Passport/Client.php +++ b/src/Passport/Client.php @@ -38,8 +38,8 @@ class Client extends Model */ protected $casts = [ 'personal_access_client' => 'bool', - 'password_client' => 'bool', - 'revoked' => 'bool', + 'password_client' => 'bool', + 'revoked' => 'bool', ]; /** diff --git a/src/Passport/PassportServiceProvider.php b/src/Passport/PassportServiceProvider.php index be2f2eaff..06c1b3735 100644 --- a/src/Passport/PassportServiceProvider.php +++ b/src/Passport/PassportServiceProvider.php @@ -15,5 +15,4 @@ public function register() $loader->alias('Laravel\Passport\Client', Client::class); $loader->alias('Laravel\Passport\PersonalAccessClient', PersonalAccessClient::class); } - } diff --git a/tests/PassportTest.php b/tests/PassportTest.php index fa2d63b11..4dc745547 100644 --- a/tests/PassportTest.php +++ b/tests/PassportTest.php @@ -3,7 +3,6 @@ use Illuminate\Support\Facades\Artisan; use Illuminate\Support\Facades\DB; - class PassportTest extends TestCase { public function setUp() @@ -19,8 +18,7 @@ public function setUp() public function testPassportInstall() { - $result=Artisan::call('passport:install',[]); - $this->assertEquals(0,$result); + $result = Artisan::call('passport:install', []); + $this->assertEquals(0, $result); } - } From a36bc4e6a7cacdc3536ed05d02d0701624f30e89 Mon Sep 17 00:00:00 2001 From: pi0 Date: Tue, 27 Sep 2016 10:37:57 +0330 Subject: [PATCH 58/88] Execution order of getMutators Fix #973 by @iceheat --- src/Eloquent/Model.php | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/Eloquent/Model.php b/src/Eloquent/Model.php index 00914b393..fda0fd57a 100644 --- a/src/Eloquent/Model.php +++ b/src/Eloquent/Model.php @@ -274,7 +274,8 @@ public function getAttribute($key) } } - return parent::getAttribute($key); + // Eloquent behaviour would prioritise the mutator, so Check for hasGetMutator first + return $this->hasGetMutator($key) ? $this->getAttributeValue($key) : parent::getAttribute($key); } /** From 6a536f67277927e5a778ca1fe4ab108d079977ec Mon Sep 17 00:00:00 2001 From: pi0 Date: Tue, 27 Sep 2016 12:26:24 +0330 Subject: [PATCH 59/88] Execution order of getMutators Fix #973 --- src/Eloquent/Model.php | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/src/Eloquent/Model.php b/src/Eloquent/Model.php index fda0fd57a..9a15f8eaa 100644 --- a/src/Eloquent/Model.php +++ b/src/Eloquent/Model.php @@ -234,6 +234,11 @@ public function getAttribute($key) return $this->getAttributeValue($key); } + // Eloquent behaviour would prioritise the mutator, so Check for hasGetMutator first + if ($this->hasGetMutator($key)){ + return $this->getAttributeValue($key); + } + $camelKey = camel_case($key); // If the "attribute" exists as a method on the model, it may be an @@ -274,8 +279,7 @@ public function getAttribute($key) } } - // Eloquent behaviour would prioritise the mutator, so Check for hasGetMutator first - return $this->hasGetMutator($key) ? $this->getAttributeValue($key) : parent::getAttribute($key); + return parent::getAttribute($key); } /** From 37669834dbc66d48222b4b4a842df8deaf9ad1be Mon Sep 17 00:00:00 2001 From: Pooya Parsa Date: Tue, 27 Sep 2016 08:56:36 +0000 Subject: [PATCH 60/88] Applied fixes from StyleCI [ci skip] [skip ci] --- src/Eloquent/Model.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Eloquent/Model.php b/src/Eloquent/Model.php index 9a15f8eaa..2f1510771 100644 --- a/src/Eloquent/Model.php +++ b/src/Eloquent/Model.php @@ -235,7 +235,7 @@ public function getAttribute($key) } // Eloquent behaviour would prioritise the mutator, so Check for hasGetMutator first - if ($this->hasGetMutator($key)){ + if ($this->hasGetMutator($key)) { return $this->getAttributeValue($key); } From 5147530fd1199b5a6af4c6e5d5903ed5994d2cf5 Mon Sep 17 00:00:00 2001 From: Pooya Parsa Date: Wed, 28 Sep 2016 15:14:51 +0000 Subject: [PATCH 61/88] Applied fixes from StyleCI [ci skip] [skip ci] --- src/Query/Builder.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Query/Builder.php b/src/Query/Builder.php index 491a5e7c3..6cb1e0ad5 100644 --- a/src/Query/Builder.php +++ b/src/Query/Builder.php @@ -1126,7 +1126,7 @@ protected function dateTimeConvertion($value) /** * Set custom options for the query. * - * @param array $options + * @param array $options * * @return $this */ From 85f1fb353a75743ae3c69ba9455ad201f41b8e12 Mon Sep 17 00:00:00 2001 From: pi0 Date: Thu, 13 Oct 2016 20:31:06 +0330 Subject: [PATCH 62/88] Fixes #26 --- composer.json | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/composer.json b/composer.json index 201a8def0..ced4857d6 100644 --- a/composer.json +++ b/composer.json @@ -39,10 +39,7 @@ "autoload": { "psr-4" :{ "Moloquent\\": "src/" - }, - "files" : [ - "src/SupportClasses/Support.php" - ] + } }, "autoload-dev": { "classmap": [ From 8432d6a6a11be55a35b415b35dcc5eb8e15c2700 Mon Sep 17 00:00:00 2001 From: pi0 Date: Thu, 13 Oct 2016 20:49:57 +0330 Subject: [PATCH 63/88] Work on fix #25 by @mlanin --- src/Passport/AuthCode.php | 50 ++++++++ src/Passport/Bridge/AccessTokenRepository.php | 39 +++++++ src/Passport/Client.php | 6 +- src/Passport/PassportServiceProvider.php | 8 +- src/Passport/Token.php | 108 ++++++++++++++++++ src/Passport/TokenRepository.php | 17 +++ 6 files changed, 223 insertions(+), 5 deletions(-) create mode 100644 src/Passport/AuthCode.php create mode 100644 src/Passport/Bridge/AccessTokenRepository.php create mode 100644 src/Passport/Token.php create mode 100644 src/Passport/TokenRepository.php diff --git a/src/Passport/AuthCode.php b/src/Passport/AuthCode.php new file mode 100644 index 000000000..f81e81133 --- /dev/null +++ b/src/Passport/AuthCode.php @@ -0,0 +1,50 @@ + 'bool', + ]; + + /** + * The attributes that should be mutated to dates. + * + * @var array + */ + protected $dates = [ + 'expires_at', + ]; + + /** + * Get the client that owns the authentication code. + * + * @return \Illuminate\Database\Eloquent\Relations\HasMany + */ + public function client() + { + return $this->hasMany(Client::class); + } +} diff --git a/src/Passport/Bridge/AccessTokenRepository.php b/src/Passport/Bridge/AccessTokenRepository.php new file mode 100644 index 000000000..f6254352f --- /dev/null +++ b/src/Passport/Bridge/AccessTokenRepository.php @@ -0,0 +1,39 @@ + $accessTokenEntity->getIdentifier(), + 'user_id' => $accessTokenEntity->getUserIdentifier(), + 'client_id' => $accessTokenEntity->getClient()->getIdentifier(), + 'scopes' => $this->formatScopesForStorage($accessTokenEntity->getScopes()), + 'revoked' => false, + ]); + + $token->save(); + } + + public function formatScopesForStorage(array $scopes) + { + return array_map(function ($scope) { + return $scope->getIdentifier(); + }, $scopes); + } + +} diff --git a/src/Passport/Client.php b/src/Passport/Client.php index 9ca3bb730..fac9fec1d 100644 --- a/src/Passport/Client.php +++ b/src/Passport/Client.php @@ -2,8 +2,6 @@ namespace Moloquent\Passport; -use Laravel\Passport\AuthCode; -use Laravel\Passport\Token; use Moloquent\Eloquent\Model; class Client extends Model @@ -38,8 +36,8 @@ class Client extends Model */ protected $casts = [ 'personal_access_client' => 'bool', - 'password_client' => 'bool', - 'revoked' => 'bool', + 'password_client' => 'bool', + 'revoked' => 'bool', ]; /** diff --git a/src/Passport/PassportServiceProvider.php b/src/Passport/PassportServiceProvider.php index 06c1b3735..135af3c72 100644 --- a/src/Passport/PassportServiceProvider.php +++ b/src/Passport/PassportServiceProvider.php @@ -9,10 +9,16 @@ class PassportServiceProvider extends ServiceProvider public function register() { /* - * Passport client extends Eloquents model by default, so we alias them. + * Passport client extends Eloquent model by default, so we alias them. */ $loader = \Illuminate\Foundation\AliasLoader::getInstance(); + + $loader->alias('Laravel\Passport\AuthCode', AuthCode::class); $loader->alias('Laravel\Passport\Client', Client::class); $loader->alias('Laravel\Passport\PersonalAccessClient', PersonalAccessClient::class); + $loader->alias('Laravel\Passport\Token', Token::class); + $loader->alias('Laravel\Passport\TokenRepository', TokenRepository::class); + + $loader->alias('Laravel\Passport\Bridge\AccessTokenRepository', Bridge\AccessTokenRepository::class); } } diff --git a/src/Passport/Token.php b/src/Passport/Token.php new file mode 100644 index 000000000..9e52b833d --- /dev/null +++ b/src/Passport/Token.php @@ -0,0 +1,108 @@ + 'array', + 'revoked' => 'bool', + ]; + + /** + * The attributes that should be mutated to dates. + * + * @var array + */ + protected $dates = [ + 'expires_at', + ]; + + /** + * Indicates if the model should be timestamped. + * + * @var bool + */ + public $timestamps = false; + + /** + * Get the client that the token belongs to. + * + * @return \Illuminate\Database\Eloquent\Relations\BelongsTo + */ + public function client() + { + return $this->belongsTo(Client::class); + } + + /** + * Determine if the token has a given scope. + * + * @param string $scope + * @return bool + */ + public function can($scope) + { + return in_array('*', $this->scopes) || + array_key_exists($scope, array_flip($this->scopes)); + } + + /** + * Determine if the token is missing a given scope. + * + * @param string $scope + * @return bool + */ + public function cant($scope) + { + return ! $this->can($scope); + } + + /** + * Revoke the token instance. + * + * @return void + */ + public function revoke() + { + $this->forceFill(['revoked' => true])->save(); + } + + /** + * Determine if the token is a transient JWT token. + * + * @return bool + */ + public function transient() + { + return false; + } +} diff --git a/src/Passport/TokenRepository.php b/src/Passport/TokenRepository.php new file mode 100644 index 000000000..507ebb236 --- /dev/null +++ b/src/Passport/TokenRepository.php @@ -0,0 +1,17 @@ +first(); + } +} From 1242e0fcc1c6f7ae1b9a04885b08e0c44cf3d1e2 Mon Sep 17 00:00:00 2001 From: Pooya Parsa Date: Thu, 13 Oct 2016 17:23:08 +0000 Subject: [PATCH 64/88] Applied fixes from StyleCI [ci skip] [skip ci] --- src/Passport/Bridge/AccessTokenRepository.php | 14 ++++---------- src/Passport/Client.php | 4 ++-- src/Passport/Token.php | 10 ++++++---- src/Passport/TokenRepository.php | 3 ++- 4 files changed, 14 insertions(+), 17 deletions(-) diff --git a/src/Passport/Bridge/AccessTokenRepository.php b/src/Passport/Bridge/AccessTokenRepository.php index f6254352f..a45a1d970 100644 --- a/src/Passport/Bridge/AccessTokenRepository.php +++ b/src/Passport/Bridge/AccessTokenRepository.php @@ -2,16 +2,11 @@ namespace Moloquent\Passport\Bridge; -use DateTime; -use Illuminate\Database\Connection; -use League\OAuth2\Server\Entities\ClientEntityInterface; use League\OAuth2\Server\Entities\AccessTokenEntityInterface; -use League\OAuth2\Server\Repositories\AccessTokenRepositoryInterface; use Moloquent\Passport\Token; class AccessTokenRepository extends \Laravel\Passport\Bridge\AccessTokenRepository { - /** * {@inheritdoc} */ @@ -19,11 +14,11 @@ public function persistNewAccessToken(AccessTokenEntityInterface $accessTokenEnt { // Use Token model to save token instead of direct database insert $token = new Token([ - 'id' => $accessTokenEntity->getIdentifier(), - 'user_id' => $accessTokenEntity->getUserIdentifier(), + 'id' => $accessTokenEntity->getIdentifier(), + 'user_id' => $accessTokenEntity->getUserIdentifier(), 'client_id' => $accessTokenEntity->getClient()->getIdentifier(), - 'scopes' => $this->formatScopesForStorage($accessTokenEntity->getScopes()), - 'revoked' => false, + 'scopes' => $this->formatScopesForStorage($accessTokenEntity->getScopes()), + 'revoked' => false, ]); $token->save(); @@ -35,5 +30,4 @@ public function formatScopesForStorage(array $scopes) return $scope->getIdentifier(); }, $scopes); } - } diff --git a/src/Passport/Client.php b/src/Passport/Client.php index fac9fec1d..30ec24a9e 100644 --- a/src/Passport/Client.php +++ b/src/Passport/Client.php @@ -36,8 +36,8 @@ class Client extends Model */ protected $casts = [ 'personal_access_client' => 'bool', - 'password_client' => 'bool', - 'revoked' => 'bool', + 'password_client' => 'bool', + 'revoked' => 'bool', ]; /** diff --git a/src/Passport/Token.php b/src/Passport/Token.php index 9e52b833d..9657022dd 100644 --- a/src/Passport/Token.php +++ b/src/Passport/Token.php @@ -33,7 +33,7 @@ class Token extends Model * @var array */ protected $casts = [ - 'scopes' => 'array', + 'scopes' => 'array', 'revoked' => 'bool', ]; @@ -66,7 +66,8 @@ public function client() /** * Determine if the token has a given scope. * - * @param string $scope + * @param string $scope + * * @return bool */ public function can($scope) @@ -78,12 +79,13 @@ public function can($scope) /** * Determine if the token is missing a given scope. * - * @param string $scope + * @param string $scope + * * @return bool */ public function cant($scope) { - return ! $this->can($scope); + return !$this->can($scope); } /** diff --git a/src/Passport/TokenRepository.php b/src/Passport/TokenRepository.php index 507ebb236..72fcb91e3 100644 --- a/src/Passport/TokenRepository.php +++ b/src/Passport/TokenRepository.php @@ -7,7 +7,8 @@ class TokenRepository extends \Laravel\Passport\TokenRepository /** * Get a token by the given ID. * - * @param string $id + * @param string $id + * * @return Token */ public function find($id) From 1a8d0a6e78b101596c1cbb83e5f45166e99f970c Mon Sep 17 00:00:00 2001 From: Maxim Lanin Date: Fri, 14 Oct 2016 10:08:34 +0300 Subject: [PATCH 65/88] Fix Passport bridge --- src/Passport/Bridge/AccessTokenRepository.php | 33 ------------------- src/Passport/PassportServiceProvider.php | 3 -- src/Passport/Token.php | 24 +++++++++++--- src/Passport/TokenRepository.php | 18 ---------- 4 files changed, 20 insertions(+), 58 deletions(-) delete mode 100644 src/Passport/Bridge/AccessTokenRepository.php delete mode 100644 src/Passport/TokenRepository.php diff --git a/src/Passport/Bridge/AccessTokenRepository.php b/src/Passport/Bridge/AccessTokenRepository.php deleted file mode 100644 index a45a1d970..000000000 --- a/src/Passport/Bridge/AccessTokenRepository.php +++ /dev/null @@ -1,33 +0,0 @@ - $accessTokenEntity->getIdentifier(), - 'user_id' => $accessTokenEntity->getUserIdentifier(), - 'client_id' => $accessTokenEntity->getClient()->getIdentifier(), - 'scopes' => $this->formatScopesForStorage($accessTokenEntity->getScopes()), - 'revoked' => false, - ]); - - $token->save(); - } - - public function formatScopesForStorage(array $scopes) - { - return array_map(function ($scope) { - return $scope->getIdentifier(); - }, $scopes); - } -} diff --git a/src/Passport/PassportServiceProvider.php b/src/Passport/PassportServiceProvider.php index 135af3c72..0f4590742 100644 --- a/src/Passport/PassportServiceProvider.php +++ b/src/Passport/PassportServiceProvider.php @@ -17,8 +17,5 @@ public function register() $loader->alias('Laravel\Passport\Client', Client::class); $loader->alias('Laravel\Passport\PersonalAccessClient', PersonalAccessClient::class); $loader->alias('Laravel\Passport\Token', Token::class); - $loader->alias('Laravel\Passport\TokenRepository', TokenRepository::class); - - $loader->alias('Laravel\Passport\Bridge\AccessTokenRepository', Bridge\AccessTokenRepository::class); } } diff --git a/src/Passport/Token.php b/src/Passport/Token.php index 9657022dd..f1f079f30 100644 --- a/src/Passport/Token.php +++ b/src/Passport/Token.php @@ -6,6 +6,13 @@ class Token extends Model { + /** + * The primary key for the model. + * + * @var string + */ + protected $primaryKey = 'id'; + /** * The database table used by the model. * @@ -33,7 +40,6 @@ class Token extends Model * @var array */ protected $casts = [ - 'scopes' => 'array', 'revoked' => 'bool', ]; @@ -47,11 +53,21 @@ class Token extends Model ]; /** - * Indicates if the model should be timestamped. + * Overwrite scopes setter to handle default passport JSON string + * and save native array. * - * @var bool + * @param mixed $scopes */ - public $timestamps = false; + public function setScopesAttribute($scopes) + { + if (is_string($scopes)) { + $scopes = json_decode($scopes, true); + } + + // If successfully decoded into array, then it will be saved as array. + // If still string, will be converted to array to preserve consistency. + $this->attributes['scopes'] = (array) $scopes; + } /** * Get the client that the token belongs to. diff --git a/src/Passport/TokenRepository.php b/src/Passport/TokenRepository.php deleted file mode 100644 index 72fcb91e3..000000000 --- a/src/Passport/TokenRepository.php +++ /dev/null @@ -1,18 +0,0 @@ -first(); - } -} From fc45b334ddc22daa27be30b789d7b21253ce1d4a Mon Sep 17 00:00:00 2001 From: hooman naghiee Date: Sun, 16 Oct 2016 16:03:19 +0330 Subject: [PATCH 66/88] Push support classes loader inside Mongo service provider --- src/MongodbServiceProvider.php | 8 ++++++++ src/SupportClasses/Support.php | 5 ----- 2 files changed, 8 insertions(+), 5 deletions(-) delete mode 100644 src/SupportClasses/Support.php diff --git a/src/MongodbServiceProvider.php b/src/MongodbServiceProvider.php index 41da289c9..aa9fc8484 100644 --- a/src/MongodbServiceProvider.php +++ b/src/MongodbServiceProvider.php @@ -16,6 +16,8 @@ public function boot() Model::setConnectionResolver($this->app['db']); Model::setEventDispatcher($this->app['events']); + + $this->loadSupportClasses(); } /** @@ -37,4 +39,10 @@ public function register() }); }); } + + private function loadSupportClasses(){ + if (!class_exists('Jenssegers\Mongodb\Eloquent\Model')) { + require_once __DIR__ . '/SupportClasses/Jenssegers/Model.php'; + } + } } diff --git a/src/SupportClasses/Support.php b/src/SupportClasses/Support.php deleted file mode 100644 index 042617fbf..000000000 --- a/src/SupportClasses/Support.php +++ /dev/null @@ -1,5 +0,0 @@ - Date: Sun, 16 Oct 2016 16:05:24 +0330 Subject: [PATCH 67/88] code style fixes --- src/MongodbServiceProvider.php | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/MongodbServiceProvider.php b/src/MongodbServiceProvider.php index aa9fc8484..af68b78d1 100644 --- a/src/MongodbServiceProvider.php +++ b/src/MongodbServiceProvider.php @@ -40,9 +40,10 @@ public function register() }); } - private function loadSupportClasses(){ + private function loadSupportClasses() + { if (!class_exists('Jenssegers\Mongodb\Eloquent\Model')) { - require_once __DIR__ . '/SupportClasses/Jenssegers/Model.php'; + require_once __DIR__.'/SupportClasses/Jenssegers/Model.php'; } } } From 46a8003c206f81c614417d6e1c14bd9b116976ce Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Michael=20L=C3=BChr?= Date: Fri, 21 Oct 2016 13:37:02 +0200 Subject: [PATCH 68/88] introduce and use schema grammar (fixes #33) --- src/Connection.php | 3 +++ src/Schema/Grammar.php | 14 ++++++++++++++ 2 files changed, 17 insertions(+) create mode 100644 src/Schema/Grammar.php diff --git a/src/Connection.php b/src/Connection.php index 8e67babc5..b8e160773 100644 --- a/src/Connection.php +++ b/src/Connection.php @@ -3,6 +3,7 @@ namespace Moloquent; use MongoDB\Client; +use Moloquent\Schema\Grammar; class Connection extends \Illuminate\Database\Connection { @@ -27,6 +28,8 @@ class Connection extends \Illuminate\Database\Connection */ public function __construct(array $config) { + $this->schemaGrammar = new Grammar(); + $this->config = $config; // Build the connection string diff --git a/src/Schema/Grammar.php b/src/Schema/Grammar.php new file mode 100644 index 000000000..ea3e53680 --- /dev/null +++ b/src/Schema/Grammar.php @@ -0,0 +1,14 @@ + Date: Mon, 31 Oct 2016 20:45:01 -0300 Subject: [PATCH 69/88] use_mongo_id and use_collection defined in the connection configuration --- src/Eloquent/Model.php | 7 ++++++- src/Query/Builder.php | 3 +++ 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/src/Eloquent/Model.php b/src/Eloquent/Model.php index 2f1510771..f56fe9349 100644 --- a/src/Eloquent/Model.php +++ b/src/Eloquent/Model.php @@ -651,7 +651,12 @@ public function hasCast($key, $types = null, $castType = 'get') */ public function useMongoId() { - return (bool) config('database.connections.mongodb.use_mongo_id', false); + if (function_exists('config')) { + return (bool) config('database.connections.mongodb.use_mongo_id', false); + } + + $connection = $this->getConnection(); + return $connection->getConfig('use_mongo_id'); } /** diff --git a/src/Query/Builder.php b/src/Query/Builder.php index 6cb1e0ad5..4f6f65317 100644 --- a/src/Query/Builder.php +++ b/src/Query/Builder.php @@ -119,6 +119,9 @@ protected function shouldUseCollections() $version = app()->version(); $version = filter_var(explode(')', $version)[0], FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION); // lumen return version_compare($version, '5.3', '>='); + } else { + $connection = $this->getConnection(); + return $connection->getConfig('use_collection'); } } From 7a12c735b6ea044ef3c341d7b796b94b698f37a5 Mon Sep 17 00:00:00 2001 From: Juan J Ibarra Date: Wed, 25 Jan 2017 09:52:49 -0400 Subject: [PATCH 70/88] Update Builder.php change access specifier on $operators property to match Laravel base [Symfony\Component\Debug\Exception\FatalErrorException] Access level to Moloquent\Query\Builder::$operators must be public (as in class Illuminate\Database\Query\Builder) --- src/Query/Builder.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Query/Builder.php b/src/Query/Builder.php index 4f6f65317..be4f373a9 100644 --- a/src/Query/Builder.php +++ b/src/Query/Builder.php @@ -62,7 +62,7 @@ class Builder extends BaseBuilder * * @var array */ - protected $operators = [ + public $operators = [ '=', '<', '>', '<=', '>=', '<>', '!=', 'like', 'not like', 'between', 'ilike', '&', '|', '^', '<<', '>>', From 9b4f30ef2a1419ac6caa0eb297cedd3d9143a6eb Mon Sep 17 00:00:00 2001 From: hooman naghiee Date: Sun, 19 Feb 2017 12:52:33 +0330 Subject: [PATCH 71/88] trim primaryKey and remove "_id" underscore from it the problem is getForeignKey return user__id but it must return user_id --- src/Eloquent/Model.php | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/src/Eloquent/Model.php b/src/Eloquent/Model.php index 2f1510771..a45451d20 100644 --- a/src/Eloquent/Model.php +++ b/src/Eloquent/Model.php @@ -6,6 +6,7 @@ use DateTime; use Illuminate\Database\Eloquent\Model as BaseModel; use Illuminate\Database\Eloquent\Relations\Relation; +use Illuminate\Support\Str; use Moloquent\Query\Builder as QueryBuilder; use Moloquent\Relations\EmbedsMany; use Moloquent\Relations\EmbedsOne; @@ -524,6 +525,16 @@ public function getParentRelation() { return $this->parentRelation; } + + /** + * Get the default foreign key name for the model. + * + * @return string + */ + public function getForeignKey() + { + return Str::snake(class_basename($this)) . '_' . trim($this->primaryKey, '_'); + } /** * Create a new Eloquent query builder for the model. From 41a18558e2d38d2d8109e5ac43c5ba57ede3d9a9 Mon Sep 17 00:00:00 2001 From: Pooya Parsa Date: Mon, 20 Mar 2017 14:43:01 +0330 Subject: [PATCH 72/88] =?UTF-8?q?=F0=9F=8C=BE=20Happy=20nowruz?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit From 6e562c1bbc45f387d9174c1a50ad3e320d3aa131 Mon Sep 17 00:00:00 2001 From: Pooya Parsa Date: Sat, 25 Mar 2017 23:02:59 +0430 Subject: [PATCH 73/88] [5.4] change otherKey to ownerKey w/backward compatibility closes #46 --- src/Relations/BelongsTo.php | 26 +++++++++++++++++++------- 1 file changed, 19 insertions(+), 7 deletions(-) mode change 100644 => 100755 src/Relations/BelongsTo.php diff --git a/src/Relations/BelongsTo.php b/src/Relations/BelongsTo.php old mode 100644 new mode 100755 index 24a8d97d3..260a5fd8d --- a/src/Relations/BelongsTo.php +++ b/src/Relations/BelongsTo.php @@ -4,6 +4,7 @@ class BelongsTo extends \Illuminate\Database\Eloquent\Relations\BelongsTo { + /** * Set the base constraints on the relation query. */ @@ -13,7 +14,7 @@ public function addConstraints() // 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}); + $this->query->where($this->getOtherKey(), '=', $this->parent->{$this->foreignKey}); } } @@ -27,7 +28,7 @@ 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; + $key = $this->getOtherKey(); $this->query->whereIn($key, $this->getEagerModelKeys($models)); } @@ -35,16 +36,17 @@ public function addEagerConstraints(array $models) /** * Match the eagerly loaded results to their parents. * - * @param array $models + * @param array $models * @param \Illuminate\Database\Eloquent\Collection $results - * @param string $relation + * @param string $relation * * @return array */ public function match(array $models, \Illuminate\Database\Eloquent\Collection $results, $relation) { $foreign = $this->foreignKey; - $other = $this->otherKey; + $other = $this->getOtherKey(); + // First we will get to build a dictionary of the child models by their primary // key of the relationship, then we can easily match the children back onto // the parents using that dictionary and the primary key of the children. @@ -56,11 +58,21 @@ public function match(array $models, \Illuminate\Database\Eloquent\Collection $r // and match back onto their children using these keys of the dictionary and // the primary key of the children to map them onto the correct instances. foreach ($models as $model) { - if (isset($dictionary[(string) $model->$foreign])) { - $model->setRelation($relation, $dictionary[(string) $model->$foreign]); + if (isset($dictionary[(string)$model->$foreign])) { + $model->setRelation($relation, $dictionary[(string)$model->$foreign]); } } return $models; } + + private function getOtherKey() + { + // Laravel >= 5.4 + if (property_exists($this, 'ownerKey')) { + return $this->ownerKey; + } + + return $this->otherKey; + } } From 1f75d4d58073df832fed9e09d4a58109a445b809 Mon Sep 17 00:00:00 2001 From: Nay Zaw Oo Date: Mon, 27 Mar 2017 23:47:37 +0630 Subject: [PATCH 74/88] Fix getOtherKey access level --- src/Relations/BelongsTo.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Relations/BelongsTo.php b/src/Relations/BelongsTo.php index 260a5fd8d..3506230df 100755 --- a/src/Relations/BelongsTo.php +++ b/src/Relations/BelongsTo.php @@ -66,7 +66,7 @@ public function match(array $models, \Illuminate\Database\Eloquent\Collection $r return $models; } - private function getOtherKey() + public function getOtherKey() { // Laravel >= 5.4 if (property_exists($this, 'ownerKey')) { From 338666bc57bdd6fe1c251375590284464f691acb Mon Sep 17 00:00:00 2001 From: Joey Houtenbos Date: Thu, 30 Mar 2017 13:46:32 +0200 Subject: [PATCH 75/88] Add missing method to get belongsToMany-caller Replace "otherKey" by "relatedKey" --- src/Eloquent/HybridRelations.php | 18 ++++++++++++++++++ src/Relations/BelongsToMany.php | 6 +++--- 2 files changed, 21 insertions(+), 3 deletions(-) diff --git a/src/Eloquent/HybridRelations.php b/src/Eloquent/HybridRelations.php index 4f8d7a477..740310e1f 100644 --- a/src/Eloquent/HybridRelations.php +++ b/src/Eloquent/HybridRelations.php @@ -262,4 +262,22 @@ public function belongsToMany($related, $collection = null, $foreignKey = null, return new BelongsToMany($query, $this, $collection, $foreignKey, $otherKey, $relation); } + + /** + * Get the relationship name of the belongs to many. + * + * @return string + */ + protected function getBelongsToManyCaller() + { + $self = __FUNCTION__; + + $caller = array_first(debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS), function ($trace) use ($self) { + $caller = $trace['function']; + + return ! in_array($caller, Model::$manyMethods) && $caller != $self; + }); + + return ! is_null($caller) ? $caller['function'] : null; + } } diff --git a/src/Relations/BelongsToMany.php b/src/Relations/BelongsToMany.php index e3599110f..d0270e719 100644 --- a/src/Relations/BelongsToMany.php +++ b/src/Relations/BelongsToMany.php @@ -116,7 +116,7 @@ public function sync($ids, $detaching = true) // 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} ?: []; + $current = $this->parent->{$this->relatedKey} ?: []; // See issue #256. if ($current instanceof Collection) { @@ -198,7 +198,7 @@ public function attach($id, array $attributes = [], $touch = true) } // Attach the new ids to the parent model. - $this->parent->push($this->otherKey, (array) $id, true); + $this->parent->push($this->relatedKey, (array) $id, true); if ($touch) { $this->touchIfTouching(); @@ -227,7 +227,7 @@ public function detach($ids = [], $touch = true) $ids = (array) $ids; // Detach all ids from the parent model. - $this->parent->pull($this->otherKey, $ids); + $this->parent->pull($this->relatedKey, $ids); // Prepare the query to select all related objects. if (count($ids) > 0) { From 647fd968fad957535786078972392e81362fe7c1 Mon Sep 17 00:00:00 2001 From: Joey Houtenbos Date: Thu, 30 Mar 2017 14:57:40 +0200 Subject: [PATCH 76/88] Use new Laravel 5.4 method to get belongsToMany-caller --- src/Eloquent/HybridRelations.php | 26 +++++++------------------- 1 file changed, 7 insertions(+), 19 deletions(-) diff --git a/src/Eloquent/HybridRelations.php b/src/Eloquent/HybridRelations.php index 740310e1f..25506da75 100644 --- a/src/Eloquent/HybridRelations.php +++ b/src/Eloquent/HybridRelations.php @@ -231,7 +231,13 @@ public function belongsToMany($related, $collection = null, $foreignKey = null, // name of the calling function. We will use that function name as the // title of this relation since that is a great convention to apply. if (is_null($relation)) { - $relation = $this->getBelongsToManyCaller(); + + // Laravel >= 5.4 + if (method_exists($this, 'guessBelongsToManyRelation')) { + $relation = $this->guessBelongsToManyRelation(); + } else { + $relation = $this->getBelongsToManyCaller(); + } } // Check if it is a relation with an original model. @@ -262,22 +268,4 @@ public function belongsToMany($related, $collection = null, $foreignKey = null, return new BelongsToMany($query, $this, $collection, $foreignKey, $otherKey, $relation); } - - /** - * Get the relationship name of the belongs to many. - * - * @return string - */ - protected function getBelongsToManyCaller() - { - $self = __FUNCTION__; - - $caller = array_first(debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS), function ($trace) use ($self) { - $caller = $trace['function']; - - return ! in_array($caller, Model::$manyMethods) && $caller != $self; - }); - - return ! is_null($caller) ? $caller['function'] : null; - } } From 9313d9faf009991a31b30677292d223a5725c426 Mon Sep 17 00:00:00 2001 From: arogozin Date: Fri, 14 Apr 2017 21:45:06 -0400 Subject: [PATCH 77/88] Update MongoQueue.php This file was missing expire property. I have also changed from DatabaseJob to MongoJob. --- src/Queue/MongoQueue.php | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) diff --git a/src/Queue/MongoQueue.php b/src/Queue/MongoQueue.php index 0a4af069d..eb208a4c2 100644 --- a/src/Queue/MongoQueue.php +++ b/src/Queue/MongoQueue.php @@ -9,6 +9,13 @@ class MongoQueue extends DatabaseQueue { + /** + * The expiration time of a job. + * + * @var int|null + */ + protected $expire = 60; + /** * Pop the next job off of the queue. * @@ -19,14 +26,14 @@ class MongoQueue extends DatabaseQueue public function pop($queue = null) { $queue = $this->getQueue($queue); - + if (!is_null($this->expire)) { $this->releaseJobsThatHaveBeenReservedTooLong($queue); } - + if ($job = $this->getNextAvailableJobAndReserve($queue)) { - return new DatabaseJob( - $this->container, $this, $job, $queue + return new MongoJob( + $this->container, $this, $job, $this->connectionName, $queue ); } } From 142c3e1520467a97ede8619d80ba9f570db610ca Mon Sep 17 00:00:00 2001 From: arogozin Date: Fri, 14 Apr 2017 21:47:26 -0400 Subject: [PATCH 78/88] Create MongoJob.php Syncing up with jenssegers/laravel-mongodb Queue MongoJob --- src/Queue/MongoJob.php | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 src/Queue/MongoJob.php diff --git a/src/Queue/MongoJob.php b/src/Queue/MongoJob.php new file mode 100644 index 000000000..bd9f700e4 --- /dev/null +++ b/src/Queue/MongoJob.php @@ -0,0 +1,25 @@ +job->reserved; + } + /** + * @return \DateTime + */ + public function reservedAt() + { + return $this->job->reserved_at; + } +} From 99fe348eed4f1508c720c28b7dc34a76270cdcf0 Mon Sep 17 00:00:00 2001 From: Amir Haghighati Date: Sun, 16 Apr 2017 01:33:59 +0430 Subject: [PATCH 79/88] Fixed relation to support many to many relations. Now the attributes in relation will be loaded (See #58). --- src/Relations/BelongsToMany.php | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/src/Relations/BelongsToMany.php b/src/Relations/BelongsToMany.php index d0270e719..e25bc1abe 100644 --- a/src/Relations/BelongsToMany.php +++ b/src/Relations/BelongsToMany.php @@ -26,6 +26,14 @@ protected function hydratePivotRelation(array $models) * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany */ protected function getSelectColumns(array $columns = ['*']) + { + return $columns; + } + + /** + * @inheritdoc + */ + protected function shouldSelect(array $columns = ['*']) { return $columns; } From 6d8422cd352dc4f93f356a1ed14dcde1e159576b Mon Sep 17 00:00:00 2001 From: Anh Pham Date: Mon, 17 Apr 2017 14:55:48 +0700 Subject: [PATCH 80/88] Fix undefined method getTime --- src/Queue/MongoQueue.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/Queue/MongoQueue.php b/src/Queue/MongoQueue.php index eb208a4c2..151f7e835 100644 --- a/src/Queue/MongoQueue.php +++ b/src/Queue/MongoQueue.php @@ -59,13 +59,13 @@ protected function getNextAvailableJobAndReserve($queue) [ 'queue' => $this->getQueue($queue), 'reserved' => 0, - 'available_at' => ['$lte' => $this->getTime()], + 'available_at' => ['$lte' => $this->currentTime()], ], [ '$set' => [ 'reserved' => 1, - 'reserved_at' => $this->getTime(), + 'reserved_at' => $this->currentTime(), ], ], [ From 81581e396803aea582113cda0c7d0d3230221961 Mon Sep 17 00:00:00 2001 From: lintaba Date: Wed, 26 Apr 2017 15:13:18 +0200 Subject: [PATCH 81/88] Aggregation shouldn't mutate querybuilder Fixes #63 --- src/Query/Builder.php | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/src/Query/Builder.php b/src/Query/Builder.php index be4f373a9..4047d680f 100644 --- a/src/Query/Builder.php +++ b/src/Query/Builder.php @@ -421,13 +421,23 @@ public function aggregate($function, $columns = []) { $this->aggregate = compact('function', 'columns'); + $previousColumns = $this->columns; + + // We will also back up the select bindings since the select clause will be + // removed when performing the aggregate function. Once the query is run + // we will add the bindings back onto this query so they can get used. + $previousSelectBindings = $this->bindings['select']; + + $this->bindings['select'] = []; + $results = $this->get($columns); // Once we have executed the query, we will reset the aggregate property so // that more select queries can be executed against the database without // the aggregate value getting in the way when the grammar builds it. - $this->columns = null; $this->aggregate = null; + $this->columns = $previousColumns; + $this->bindings['select'] = $previousSelectBindings; if (isset($results[0])) { $result = (array) $results[0]; From f6f63bea5f886355a754783ea19976208e224b37 Mon Sep 17 00:00:00 2001 From: Thiago Carnaes Date: Thu, 1 Jun 2017 14:19:25 -0300 Subject: [PATCH 82/88] Update PasswordBrokerManager.php Add $this->app['hash'] to get token to reset password --- src/Auth/PasswordBrokerManager.php | 1 + 1 file changed, 1 insertion(+) diff --git a/src/Auth/PasswordBrokerManager.php b/src/Auth/PasswordBrokerManager.php index 58b7465e5..82d3b0349 100644 --- a/src/Auth/PasswordBrokerManager.php +++ b/src/Auth/PasswordBrokerManager.php @@ -17,6 +17,7 @@ protected function createTokenRepository(array $config) { return new DatabaseTokenRepository( $this->app['db']->connection(), + $this->app['hash'], $config['table'], $this->app['config']['app.key'], $config['expire'] From 3c562a69edf8da1d8ee38ca8066d5c5a980c25b5 Mon Sep 17 00:00:00 2001 From: Thiago Carnaes Date: Thu, 1 Jun 2017 15:06:38 -0300 Subject: [PATCH 83/88] Update DatabaseTokenRepository.php Update in function getPayload in created_at Update in function tokenExpired, change the variable $token to $createdAt --- src/Auth/DatabaseTokenRepository.php | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/src/Auth/DatabaseTokenRepository.php b/src/Auth/DatabaseTokenRepository.php index bde6f1307..d2479200d 100644 --- a/src/Auth/DatabaseTokenRepository.php +++ b/src/Auth/DatabaseTokenRepository.php @@ -19,29 +19,29 @@ class DatabaseTokenRepository extends BaseDatabaseTokenRepository */ protected function getPayload($email, $token) { - return ['email' => $email, 'token' => $token, 'created_at' => new UTCDateTime(round(microtime(true) * 1000))]; + return ['email' => $email, 'token' => $this->hasher->make($token), 'created_at' => new UTCDateTime(time() * 1000)]; } /** * Determine if the token has expired. * - * @param array $token + * @param array $createdAt * * @return bool */ - protected function tokenExpired($token) + protected function tokenExpired($createdAt) { // Convert UTCDateTime to a date string. - if ($token['created_at'] instanceof UTCDateTime) { - $date = $token['created_at']->toDateTime(); + if ($createdAt instanceof UTCDateTime) { + $date = $createdAt->toDateTime(); $date->setTimezone(new DateTimeZone(date_default_timezone_get())); - $token['created_at'] = $date->format('Y-m-d H:i:s'); - } elseif (is_array($token['created_at']) and isset($token['created_at']['date'])) { - $date = new DateTime($token['created_at']['date'], new DateTimeZone(isset($token['created_at']['timezone']) ? $token['created_at']['timezone'] : 'UTC')); + $createdAt = $date->format('Y-m-d H:i:s'); + } elseif (is_array($createdAt) and isset($createdAt['date'])) { + $date = new DateTime($createdAt['date'], new DateTimeZone(isset($createdAt['timezone']) ? $createdAt['timezone'] : 'UTC')); $date->setTimezone(new DateTimeZone(date_default_timezone_get())); - $token['created_at'] = $date->format('Y-m-d H:i:s'); + $createdAt = $date->format('Y-m-d H:i:s'); } - return parent::tokenExpired($token); + return parent::tokenExpired($createdAt); } } From e5ae4baa82ae0de94561271e16c936d03439d7b9 Mon Sep 17 00:00:00 2001 From: Thiago Carnaes Date: Thu, 1 Jun 2017 15:55:22 -0300 Subject: [PATCH 84/88] Update DatabaseTokenRepository.php Change the the function getPayload and tokenExpired --- src/Auth/DatabaseTokenRepository.php | 17 +++-------------- 1 file changed, 3 insertions(+), 14 deletions(-) diff --git a/src/Auth/DatabaseTokenRepository.php b/src/Auth/DatabaseTokenRepository.php index d2479200d..46707d56a 100644 --- a/src/Auth/DatabaseTokenRepository.php +++ b/src/Auth/DatabaseTokenRepository.php @@ -2,10 +2,10 @@ namespace Moloquent\Auth; +use Carbon\Carbon; use DateTime; use DateTimeZone; use Illuminate\Auth\Passwords\DatabaseTokenRepository as BaseDatabaseTokenRepository; -use MongoDB\BSON\UTCDateTime; class DatabaseTokenRepository extends BaseDatabaseTokenRepository { @@ -19,7 +19,7 @@ class DatabaseTokenRepository extends BaseDatabaseTokenRepository */ protected function getPayload($email, $token) { - return ['email' => $email, 'token' => $this->hasher->make($token), 'created_at' => new UTCDateTime(time() * 1000)]; + return ['email' => $email, 'token' => $this->hasher->make($token), 'created_at' => new Carbon]; } /** @@ -31,17 +31,6 @@ protected function getPayload($email, $token) */ protected function tokenExpired($createdAt) { - // Convert UTCDateTime to a date string. - if ($createdAt instanceof UTCDateTime) { - $date = $createdAt->toDateTime(); - $date->setTimezone(new DateTimeZone(date_default_timezone_get())); - $createdAt = $date->format('Y-m-d H:i:s'); - } elseif (is_array($createdAt) and isset($createdAt['date'])) { - $date = new DateTime($createdAt['date'], new DateTimeZone(isset($createdAt['timezone']) ? $createdAt['timezone'] : 'UTC')); - $date->setTimezone(new DateTimeZone(date_default_timezone_get())); - $createdAt = $date->format('Y-m-d H:i:s'); - } - - return parent::tokenExpired($createdAt); + return Carbon::parse($createdAt['date'])->addSeconds($this->expires)->isPast(); } } From d7321f223a19db7ad0a847c650a2668e7cb4bca8 Mon Sep 17 00:00:00 2001 From: Will Taylor-Jackson Date: Wed, 21 Jun 2017 12:42:33 +0100 Subject: [PATCH 85/88] Gets key name from model rather than assuming _id --- src/Relations/EmbedsMany.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/Relations/EmbedsMany.php b/src/Relations/EmbedsMany.php index 4279e5c80..894f759a5 100644 --- a/src/Relations/EmbedsMany.php +++ b/src/Relations/EmbedsMany.php @@ -251,8 +251,8 @@ public function attach(Model $model) protected function associateNew($model) { // Create a new key if needed. - if (!$model->getAttribute('_id')) { - $model->setAttribute('_id', new ObjectID()); + if (!$model->getKey()) { + $model->setAttribute($model->getKeyName(), new ObjectID()); } $records = $this->getEmbedded(); From f5c810eacfbbf4ceca0fcc44f08d96db400af7e6 Mon Sep 17 00:00:00 2001 From: Juan J Ibarra Date: Wed, 13 Sep 2017 13:09:39 -0400 Subject: [PATCH 86/88] Update HybridRelations.php Error with new official released Laravel 5.5 Declaration of Moloquent\Eloquent\HybridRelations::belongsToMany($related, $collection = NULL, $foreignKey = NULL, $otherKey = NULL, $relation = NULL) should be compatible with Illuminate\Database\Eloquent\Model::belongsToMany($related, $table = NULL, $foreignPivotKey = NULL, $relatedPivotKey = NULL, $parentKey = NULL, $relatedKey = NULL, $relation = NULL) update to laravel 5.5 --- src/Eloquent/HybridRelations.php | 21 +++++++++++++-------- 1 file changed, 13 insertions(+), 8 deletions(-) diff --git a/src/Eloquent/HybridRelations.php b/src/Eloquent/HybridRelations.php index 25506da75..29c8ae415 100644 --- a/src/Eloquent/HybridRelations.php +++ b/src/Eloquent/HybridRelations.php @@ -217,15 +217,18 @@ public function morphTo($name = null, $type = null, $id = null) /** * Define a many-to-many relationship. * - * @param string $related - * @param string $collection - * @param string $foreignKey - * @param string $otherKey - * @param string $relation + * @param string $related + * @param string $table + * @param string $foreignPivotKey + * @param string $relatedPivotKey + * @param string $parentKey + * @param string $relatedKey + * @param string $relation * * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany */ - public function belongsToMany($related, $collection = null, $foreignKey = null, $otherKey = null, $relation = null) + public function belongsToMany($related, $table = null, $foreignPivotKey = null, $relatedPivotKey = null, + $parentKey = null, $relatedKey = null, $relation = null) { // If no relationship name was passed, we will pull backtraces to get the // name of the calling function. We will use that function name as the @@ -242,7 +245,8 @@ public function belongsToMany($related, $collection = null, $foreignKey = null, // Check if it is a relation with an original model. if (!is_subclass_of($related, 'Moloquent\Eloquent\Model')) { - return parent::belongsToMany($related, $collection, $foreignKey, $otherKey, $relation); + return parent::belongsToMany($related, $table = null, $foreignPivotKey = null, $relatedPivotKey = null, + $parentKey = null, $relatedKey = null, $relation = null); } // First, we'll need to determine the foreign key and "other key" for the @@ -266,6 +270,7 @@ public function belongsToMany($related, $collection = null, $foreignKey = null, // appropriate query constraint and entirely manages the hydrations. $query = $instance->newQuery(); - return new BelongsToMany($query, $this, $collection, $foreignKey, $otherKey, $relation); + return new BelongsToMany($related, $table = null, $foreignPivotKey = null, $relatedPivotKey = null, + $parentKey = null, $relatedKey = null, $relation = null); } } From 36b56880e22075e2cb6eadb03beea363dfd15c47 Mon Sep 17 00:00:00 2001 From: Pooya Parsa Date: Wed, 20 Sep 2017 17:53:50 +0430 Subject: [PATCH 87/88] handle array_walk_recursive exceptions --- src/Collection.php | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/src/Collection.php b/src/Collection.php index 8082eeab5..ea6642971 100644 --- a/src/Collection.php +++ b/src/Collection.php @@ -53,11 +53,15 @@ public function __call($method, $parameters) $query = []; // Convert the query parameters to a json string. - array_walk_recursive($parameters, function (&$item, $key) { - if ($item instanceof ObjectID) { - $item = (string) $item; - } - }); + try { + array_walk_recursive($parameters, function (&$item, $key) { + if ($item instanceof ObjectID) { + $item = (string) $item; + } + }); + } catch (Exception $e) { + // Ignore + } // Convert the query parameters to a json string. foreach ($parameters as $parameter) { From ffd35f4f84d3ac3c32f134af46cae5451a7e904d Mon Sep 17 00:00:00 2001 From: Will Taylor-Jackson Date: Thu, 21 Sep 2017 12:55:21 +0100 Subject: [PATCH 88/88] Fixes getting relationship by using camelKey instead of key --- src/Eloquent/Model.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/Eloquent/Model.php b/src/Eloquent/Model.php index f5c367b57..9f2794a04 100644 --- a/src/Eloquent/Model.php +++ b/src/Eloquent/Model.php @@ -263,7 +263,7 @@ public function getAttribute($key) } // Get the relation results. - return $this->getRelationshipFromMethod($key, $camelKey); + return $this->getRelationshipFromMethod($camelKey); } if ($relations instanceof Relation) { @@ -275,7 +275,7 @@ public function getAttribute($key) } // Get the relation results. - return $this->getRelationshipFromMethod($key, $camelKey); + return $this->getRelationshipFromMethod($camelKey); } } }