From 01ad545a128f2a0bdb8047588bc73f6af72cc8cc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=A9r=C3=B4me=20Tamarelle?= Date: Wed, 10 Jul 2024 14:47:10 +0200 Subject: [PATCH 01/10] PHPORM-147 Make id an alias for _id --- CHANGELOG.md | 4 ++ src/Query/Builder.php | 28 ++++++----- tests/Query/BuilderTest.php | 94 ++++++++++++++++++++----------------- tests/QueryBuilderTest.php | 17 +++++++ tests/SessionTest.php | 33 +++++++++++++ 5 files changed, 122 insertions(+), 54 deletions(-) create mode 100644 tests/SessionTest.php diff --git a/CHANGELOG.md b/CHANGELOG.md index 5f2a2f9e5..b6cb17ced 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,10 @@ # Changelog All notable changes to this project will be documented in this file. +# [4.7.0] - upcoming + +* **BREAKING CHANGE** Use `id` and an alias for `_id` in commands and queries for compatibility with Eloquent packages by @GromNaN in [#3040](https://github.com/mongodb/laravel-mongodb/pull/3040) + ## [4.6.0] - 2024-07-09 * Add `DocumentModel` trait to use any 3rd party model with MongoDB @GromNaN in [#2580](https://github.com/mongodb/laravel-mongodb/pull/2580) diff --git a/src/Query/Builder.php b/src/Query/Builder.php index 89faa4b17..00846d3ed 100644 --- a/src/Query/Builder.php +++ b/src/Query/Builder.php @@ -682,6 +682,17 @@ public function insert(array $values) $values = [$values]; } + // Compatibility with Eloquent queries that uses "id" instead of MongoDB's _id + foreach ($values as &$document) { + if (isset($document['id'])) { + if (isset($document['_id']) && $document['_id'] !== $document['id']) { + throw new InvalidArgumentException('Cannot insert document with different "id" and "_id" values'); + } + + $document['_id'] = $document['id']; + } + } + $options = $this->inheritConnectionOptions(); $result = $this->collection->insertMany($values, $options); @@ -752,18 +763,6 @@ public function decrement($column, $amount = 1, array $extra = [], array $option return $this->increment($column, -1 * $amount, $extra, $options); } - /** @inheritdoc */ - public function chunkById($count, callable $callback, $column = '_id', $alias = null) - { - return parent::chunkById($count, $callback, $column, $alias); - } - - /** @inheritdoc */ - public function forPageAfterId($perPage = 15, $lastId = 0, $column = '_id') - { - return parent::forPageAfterId($perPage, $lastId, $column); - } - /** @inheritdoc */ public function pluck($column, $key = null) { @@ -1039,6 +1038,11 @@ public function where($column, $operator = null, $value = null, $boolean = 'and' { $params = func_get_args(); + // Compatibility with Eloquent queries that uses "id" instead of MongoDB's _id + if ($column === 'id') { + $params[0] = $column = '_id'; + } + // Remove the leading $ from operators. if (func_num_args() >= 3) { $operator = &$params[1]; diff --git a/tests/Query/BuilderTest.php b/tests/Query/BuilderTest.php index 3ec933499..bb62efbfa 100644 --- a/tests/Query/BuilderTest.php +++ b/tests/Query/BuilderTest.php @@ -135,21 +135,21 @@ public static function provideQueryBuilderToMql(): iterable 'find' => [ [ '$or' => [ - ['id' => 1], - ['id' => ['$in' => [1, 2, 3]]], + ['foo' => 1], + ['foo' => ['$in' => [1, 2, 3]]], ], ], [], // options ], ], - fn (Builder $builder) => $builder->where('id', '=', 1) - ->orWhereIn('id', [1, 2, 3]), + fn (Builder $builder) => $builder->where('foo', '=', 1) + ->orWhereIn('foo', [1, 2, 3]), ]; /** @see DatabaseQueryBuilderTest::testBasicWhereNotIns */ yield 'whereNotIn' => [ - ['find' => [['id' => ['$nin' => [1, 2, 3]]], []]], - fn (Builder $builder) => $builder->whereNotIn('id', [1, 2, 3]), + ['find' => [['foo' => ['$nin' => [1, 2, 3]]], []]], + fn (Builder $builder) => $builder->whereNotIn('foo', [1, 2, 3]), ]; yield 'orWhereNotIn' => [ @@ -157,15 +157,15 @@ public static function provideQueryBuilderToMql(): iterable 'find' => [ [ '$or' => [ - ['id' => 1], - ['id' => ['$nin' => [1, 2, 3]]], + ['foo' => 1], + ['foo' => ['$nin' => [1, 2, 3]]], ], ], [], // options ], ], - fn (Builder $builder) => $builder->where('id', '=', 1) - ->orWhereNotIn('id', [1, 2, 3]), + fn (Builder $builder) => $builder->where('foo', '=', 1) + ->orWhereNotIn('foo', [1, 2, 3]), ]; /** @see DatabaseQueryBuilderTest::testEmptyWhereIns */ @@ -220,7 +220,7 @@ public static function provideQueryBuilderToMql(): iterable 'find' => [ [ '$or' => [ - ['id' => 1], + ['age' => 1], ['email' => 'foo'], ], ], @@ -228,7 +228,7 @@ public static function provideQueryBuilderToMql(): iterable ], ], fn (Builder $builder) => $builder - ->where('id', '=', 1) + ->where('age', '=', 1) ->orWhere('email', '=', 'foo'), ]; @@ -589,16 +589,16 @@ function (Builder $builder) { 'find' => [ [ '$or' => [ - ['id' => 1], - ['id' => ['$gte' => 3, '$lte' => 5]], + ['age' => 1], + ['age' => ['$gte' => 3, '$lte' => 5]], ], ], [], // options ], ], fn (Builder $builder) => $builder - ->where('id', '=', 1) - ->orWhereBetween('id', [3, 5]), + ->where('age', '=', 1) + ->orWhereBetween('age', [3, 5]), ]; /** @link https://www.mongodb.com/docs/manual/reference/bson-type-comparison-order/#arrays */ @@ -607,16 +607,16 @@ function (Builder $builder) { 'find' => [ [ '$or' => [ - ['id' => 1], - ['id' => ['$gte' => [4], '$lte' => [6, 8]]], + ['age' => 1], + ['age' => ['$gte' => [4], '$lte' => [6, 8]]], ], ], [], // options ], ], fn (Builder $builder) => $builder - ->where('id', '=', 1) - ->orWhereBetween('id', [[4], [6, 8]]), + ->where('age', '=', 1) + ->orWhereBetween('age', [[4], [6, 8]]), ]; yield 'orWhereBetween collection' => [ @@ -624,16 +624,16 @@ function (Builder $builder) { 'find' => [ [ '$or' => [ - ['id' => 1], - ['id' => ['$gte' => 3, '$lte' => 4]], + ['age' => 1], + ['age' => ['$gte' => 3, '$lte' => 4]], ], ], [], // options ], ], fn (Builder $builder) => $builder - ->where('id', '=', 1) - ->orWhereBetween('id', collect([3, 4])), + ->where('age', '=', 1) + ->orWhereBetween('age', collect([3, 4])), ]; yield 'whereNotBetween array of numbers' => [ @@ -641,14 +641,14 @@ function (Builder $builder) { 'find' => [ [ '$or' => [ - ['id' => ['$lte' => 1]], - ['id' => ['$gte' => 2]], + ['age' => ['$lte' => 1]], + ['age' => ['$gte' => 2]], ], ], [], // options ], ], - fn (Builder $builder) => $builder->whereNotBetween('id', [1, 2]), + fn (Builder $builder) => $builder->whereNotBetween('age', [1, 2]), ]; /** @see DatabaseQueryBuilderTest::testOrWhereNotBetween() */ @@ -657,11 +657,11 @@ function (Builder $builder) { 'find' => [ [ '$or' => [ - ['id' => 1], + ['age' => 1], [ '$or' => [ - ['id' => ['$lte' => 3]], - ['id' => ['$gte' => 5]], + ['age' => ['$lte' => 3]], + ['age' => ['$gte' => 5]], ], ], ], @@ -670,8 +670,8 @@ function (Builder $builder) { ], ], fn (Builder $builder) => $builder - ->where('id', '=', 1) - ->orWhereNotBetween('id', [3, 5]), + ->where('age', '=', 1) + ->orWhereNotBetween('age', [3, 5]), ]; yield 'orWhereNotBetween nested array of numbers' => [ @@ -679,11 +679,11 @@ function (Builder $builder) { 'find' => [ [ '$or' => [ - ['id' => 1], + ['age' => 1], [ '$or' => [ - ['id' => ['$lte' => [2, 3]]], - ['id' => ['$gte' => [5]]], + ['age' => ['$lte' => [2, 3]]], + ['age' => ['$gte' => [5]]], ], ], ], @@ -692,8 +692,8 @@ function (Builder $builder) { ], ], fn (Builder $builder) => $builder - ->where('id', '=', 1) - ->orWhereNotBetween('id', [[2, 3], [5]]), + ->where('age', '=', 1) + ->orWhereNotBetween('age', [[2, 3], [5]]), ]; yield 'orWhereNotBetween collection' => [ @@ -701,11 +701,11 @@ function (Builder $builder) { 'find' => [ [ '$or' => [ - ['id' => 1], + ['age' => 1], [ '$or' => [ - ['id' => ['$lte' => 3]], - ['id' => ['$gte' => 4]], + ['age' => ['$lte' => 3]], + ['age' => ['$gte' => 4]], ], ], ], @@ -714,8 +714,8 @@ function (Builder $builder) { ], ], fn (Builder $builder) => $builder - ->where('id', '=', 1) - ->orWhereNotBetween('id', collect([3, 4])), + ->where('age', '=', 1) + ->orWhereNotBetween('age', collect([3, 4])), ]; yield 'where like' => [ @@ -1160,6 +1160,16 @@ function (Builder $elemMatchQuery): void { ), ]; + yield 'id alias for _id' => [ + ['find' => [['_id' => 1], []]], + fn (Builder $builder) => $builder->where('id', 1), + ]; + + yield 'id alias for _id with $or' => [ + ['find' => [['$or' => [['_id' => 1], ['_id' => 2]]], []]], + fn (Builder $builder) => $builder->where('id', 1)->orWhere('id', 2), + ]; + // Method added in Laravel v10.47.0 if (method_exists(Builder::class, 'whereAll')) { /** @see DatabaseQueryBuilderTest::testWhereAll */ diff --git a/tests/QueryBuilderTest.php b/tests/QueryBuilderTest.php index 4320e6a54..0163bdeae 100644 --- a/tests/QueryBuilderTest.php +++ b/tests/QueryBuilderTest.php @@ -24,6 +24,7 @@ use MongoDB\Laravel\Query\Builder; use MongoDB\Laravel\Tests\Models\Item; use MongoDB\Laravel\Tests\Models\User; +use PHPUnit\Framework\Attributes\TestWith; use Stringable; use function count; @@ -964,4 +965,20 @@ public function testStringableColumn() $user = DB::collection('users')->where($ageColumn, 29)->first(); $this->assertEquals('John Doe', $user['name']); } + + #[TestWith(['id', 'id'])] + #[TestWith(['id', '_id'])] + #[TestWith(['_id', 'id'])] + public function testIdAlias($insertId, $queryId): void + { + DB::collection('items')->insert([$insertId => 'abc', 'name' => 'Karting']); + $item = DB::collection('items')->where($queryId, '=', 'abc')->first(); + $this->assertNotNull($item); + $this->assertSame('abc', $item['_id']); + $this->assertSame('Karting', $item['name']); + + DB::collection('items')->where($insertId, '=', 'abc')->update(['name' => 'Bike']); + $item = DB::collection('items')->where($queryId, '=', 'abc')->first(); + $this->assertSame('Bike', $item['name']); + } } diff --git a/tests/SessionTest.php b/tests/SessionTest.php new file mode 100644 index 000000000..7ffbb51f0 --- /dev/null +++ b/tests/SessionTest.php @@ -0,0 +1,33 @@ +getCollection('sessions')->drop(); + + parent::tearDown(); + } + + public function testDatabaseSessionHandler() + { + $sessionId = '123'; + + $handler = new DatabaseSessionHandler( + $this->app['db']->connection('mongodb'), + 'sessions', + 10, + ); + + $handler->write($sessionId, 'foo'); + $this->assertEquals('foo', $handler->read($sessionId)); + + $handler->write($sessionId, 'bar'); + $this->assertEquals('bar', $handler->read($sessionId)); + } +} From eee519be8bdb5857827db0f470981bc527341f2e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=A9r=C3=B4me=20Tamarelle?= Date: Thu, 11 Jul 2024 08:57:22 +0200 Subject: [PATCH 02/10] Fix id alias in nested array --- src/Query/Builder.php | 28 ++++++++++++++-------------- tests/Query/BuilderTest.php | 11 ++++++----- 2 files changed, 20 insertions(+), 19 deletions(-) diff --git a/src/Query/Builder.php b/src/Query/Builder.php index 00846d3ed..4b8ccf245 100644 --- a/src/Query/Builder.php +++ b/src/Query/Builder.php @@ -1038,11 +1038,6 @@ public function where($column, $operator = null, $value = null, $boolean = 'and' { $params = func_get_args(); - // Compatibility with Eloquent queries that uses "id" instead of MongoDB's _id - if ($column === 'id') { - $params[0] = $column = '_id'; - } - // Remove the leading $ from operators. if (func_num_args() >= 3) { $operator = &$params[1]; @@ -1090,16 +1085,21 @@ protected function compileWheres(): array // Convert column name to string to use as array key if (isset($where['column'])) { $where['column'] = (string) $where['column']; - } - // Convert id's. - if (isset($where['column']) && ($where['column'] === '_id' || str_ends_with($where['column'], '._id'))) { - if (isset($where['values'])) { - // Multiple values. - $where['values'] = array_map($this->convertKey(...), $where['values']); - } elseif (isset($where['value'])) { - // Single value. - $where['value'] = $this->convertKey($where['value']); + // Compatibility with Eloquent queries that uses "id" instead of MongoDB's _id + if ($where['column'] === 'id') { + $where['column'] = '_id'; + } + + // Convert id's. + if ($where['column'] === '_id' || str_ends_with($where['column'], '._id')) { + if (isset($where['values'])) { + // Multiple values. + $where['values'] = array_map($this->convertKey(...), $where['values']); + } elseif (isset($where['value'])) { + // Single value. + $where['value'] = $this->convertKey($where['value']); + } } } diff --git a/tests/Query/BuilderTest.php b/tests/Query/BuilderTest.php index bb62efbfa..79c0d39e4 100644 --- a/tests/Query/BuilderTest.php +++ b/tests/Query/BuilderTest.php @@ -124,9 +124,10 @@ public static function provideQueryBuilderToMql(): iterable ]; // Nested array are not flattened like in the Eloquent builder. MongoDB can compare objects. + // When id is used as data field name, it's not converted to _id $array = [['issue' => 45582], ['id' => 2], [3]]; yield 'whereIn nested array' => [ - ['find' => [['id' => ['$in' => $array]], []]], + ['find' => [['_id' => ['$in' => $array]], []]], fn (Builder $builder) => $builder->whereIn('id', $array), ]; @@ -170,7 +171,7 @@ public static function provideQueryBuilderToMql(): iterable /** @see DatabaseQueryBuilderTest::testEmptyWhereIns */ yield 'whereIn empty array' => [ - ['find' => [['id' => ['$in' => []]], []]], + ['find' => [['_id' => ['$in' => []]], []]], fn (Builder $builder) => $builder->whereIn('id', []), ]; @@ -553,12 +554,12 @@ function (Builder $builder) { /** @see DatabaseQueryBuilderTest::testWhereBetweens() */ yield 'whereBetween array of numbers' => [ - ['find' => [['id' => ['$gte' => 1, '$lte' => 2]], []]], + ['find' => [['_id' => ['$gte' => 1, '$lte' => 2]], []]], fn (Builder $builder) => $builder->whereBetween('id', [1, 2]), ]; yield 'whereBetween nested array of numbers' => [ - ['find' => [['id' => ['$gte' => [1], '$lte' => [2, 3]]], []]], + ['find' => [['_id' => ['$gte' => [1], '$lte' => [2, 3]]], []]], fn (Builder $builder) => $builder->whereBetween('id', [[1], [2, 3]]), ]; @@ -579,7 +580,7 @@ function (Builder $builder) { ]; yield 'whereBetween collection' => [ - ['find' => [['id' => ['$gte' => 1, '$lte' => 2]], []]], + ['find' => [['_id' => ['$gte' => 1, '$lte' => 2]], []]], fn (Builder $builder) => $builder->whereBetween('id', collect([1, 2])), ]; From fdfe31d2889738a5070cc28347c0d390ecd4c996 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=A9r=C3=B4me=20Tamarelle?= Date: Thu, 11 Jul 2024 09:17:30 +0200 Subject: [PATCH 03/10] Update CHANGELOG.md Co-authored-by: Andreas Braun --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index b6cb17ced..c3ad639a0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,7 +3,7 @@ All notable changes to this project will be documented in this file. # [4.7.0] - upcoming -* **BREAKING CHANGE** Use `id` and an alias for `_id` in commands and queries for compatibility with Eloquent packages by @GromNaN in [#3040](https://github.com/mongodb/laravel-mongodb/pull/3040) +* **BREAKING CHANGE** Use `id` as an alias for `_id` in commands and queries for compatibility with Eloquent packages by @GromNaN in [#3040](https://github.com/mongodb/laravel-mongodb/pull/3040) ## [4.6.0] - 2024-07-09 From 715b68c3144a93c67a76114faee28d181aa95daa Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=A9r=C3=B4me=20Tamarelle?= Date: Thu, 11 Jul 2024 15:15:31 +0200 Subject: [PATCH 04/10] Alias id to _id for sorting --- src/Query/Builder.php | 16 +++++++++++++--- tests/Query/BuilderTest.php | 10 ++++++++++ 2 files changed, 23 insertions(+), 3 deletions(-) diff --git a/src/Query/Builder.php b/src/Query/Builder.php index 4b8ccf245..5304ace8e 100644 --- a/src/Query/Builder.php +++ b/src/Query/Builder.php @@ -375,7 +375,7 @@ public function toMql(): array // Apply order and limit if ($this->orders) { - $pipeline[] = ['$sort' => $this->orders]; + $pipeline[] = ['$sort' => $this->renameId($this->orders)]; } if ($this->offset) { @@ -416,7 +416,7 @@ public function toMql(): array // Normal query // Convert select columns to simple projections. - $projection = array_fill_keys($columns, true); + $projection = $this->renameId(array_fill_keys($columns, true)); // Add custom projections. if ($this->projections) { @@ -431,7 +431,7 @@ public function toMql(): array } if ($this->orders) { - $options['sort'] = $this->orders; + $options['sort'] = $this->renameId($this->orders); } if ($this->offset) { @@ -1539,4 +1539,14 @@ public function orWhereIntegerNotInRaw($column, $values, $boolean = 'and') { throw new BadMethodCallException('This method is not supported by MongoDB'); } + + private function renameId(array $values): array + { + if (isset($values['id'])) { + $values['_id'] = $values['id']; + unset($values['id']); + } + + return $values; + } } diff --git a/tests/Query/BuilderTest.php b/tests/Query/BuilderTest.php index 79c0d39e4..05263981e 100644 --- a/tests/Query/BuilderTest.php +++ b/tests/Query/BuilderTest.php @@ -498,6 +498,11 @@ public static function provideQueryBuilderToMql(): iterable ->orderBy('age', 'desc'), ]; + yield 'orders by id field' => [ + ['find' => [[], ['sort' => ['_id' => 1]]]], + fn (Builder $builder) => $builder->orderBy('id'), + ]; + yield 'orders = null' => [ ['find' => [[], []]], function (Builder $builder) { @@ -1171,6 +1176,11 @@ function (Builder $elemMatchQuery): void { fn (Builder $builder) => $builder->where('id', 1)->orWhere('id', 2), ]; + yield 'select colums with id alias' => [ + ['find' => [[], ['projection' => ['name' => 1, 'email' => 1, '_id' => 1]]]], + fn (Builder $builder) => $builder->select('name', 'email', 'id'), + ]; + // Method added in Laravel v10.47.0 if (method_exists(Builder::class, 'whereAll')) { /** @see DatabaseQueryBuilderTest::testWhereAll */ From 2c714611afa3eae0bd13f9b0a5693a671069d68a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=A9r=C3=B4me=20Tamarelle?= Date: Thu, 11 Jul 2024 16:20:35 +0200 Subject: [PATCH 05/10] Apply id alias to sort and results --- src/Query/Builder.php | 55 ++++++++++++++++++++++++++++++------------- 1 file changed, 39 insertions(+), 16 deletions(-) diff --git a/src/Query/Builder.php b/src/Query/Builder.php index 5304ace8e..65e6aa2c9 100644 --- a/src/Query/Builder.php +++ b/src/Query/Builder.php @@ -375,7 +375,7 @@ public function toMql(): array // Apply order and limit if ($this->orders) { - $pipeline[] = ['$sort' => $this->renameId($this->orders)]; + $pipeline[] = ['$sort' => $this->aliasIdForQuery($this->orders)]; } if ($this->offset) { @@ -416,7 +416,7 @@ public function toMql(): array // Normal query // Convert select columns to simple projections. - $projection = $this->renameId(array_fill_keys($columns, true)); + $projection = $this->aliasIdForQuery(array_fill_keys($columns, true)); // Add custom projections. if ($this->projections) { @@ -431,7 +431,7 @@ public function toMql(): array } if ($this->orders) { - $options['sort'] = $this->renameId($this->orders); + $options['sort'] = $this->aliasIdForQuery($this->orders); } if ($this->offset) { @@ -506,7 +506,7 @@ public function getFresh($columns = [], $returnLazy = false) if ($returnLazy) { return LazyCollection::make(function () use ($result) { foreach ($result as $item) { - yield $item; + yield $this->aliasIdForResult($item); } }); } @@ -515,6 +515,10 @@ public function getFresh($columns = [], $returnLazy = false) $result = $result->toArray(); } + foreach ($result as &$document) { + $document = $this->aliasIdForResult($document); + } + return new Collection($result); } @@ -593,7 +597,7 @@ public function aggregate($function = null, $columns = ['*']) /** @inheritdoc */ public function exists() { - return $this->first(['_id']) !== null; + return $this->first(['id']) !== null; } /** @inheritdoc */ @@ -690,6 +694,7 @@ public function insert(array $values) } $document['_id'] = $document['id']; + unset($document['id']); } } @@ -711,11 +716,10 @@ public function insertGetId(array $values, $sequence = null) return null; } - if ($sequence === null || $sequence === '_id') { - return $result->getInsertedId(); - } - - return $values[$sequence]; + return match ($sequence) { + '_id', 'id', null => $result->getInsertedId(), + default => $values[$sequence], + }; } /** @inheritdoc */ @@ -731,7 +735,12 @@ public function update(array $values, array $options = []) unset($values[$key]); } - $options = $this->inheritConnectionOptions($options); + // Since "id" is an alias for "_id", we prevent updating it + foreach ($values as $fields) { + if (array_key_exists('id', $fields)) { + throw new InvalidArgumentException('Cannot update "id" field.'); + } + } return $this->performUpdate($values, $options); } @@ -978,21 +987,26 @@ public function runPaginationCountQuery($columns = ['*']) /** * Perform an update query. * - * @param array $query - * * @return int */ - protected function performUpdate($query, array $options = []) + protected function performUpdate(array $update, array $options = []) { // Update multiple items by default. if (! array_key_exists('multiple', $options)) { $options['multiple'] = true; } + // Since "id" is an alias for "_id", we prevent updating it + foreach ($update as $operator => $fields) { + if (array_key_exists('id', $fields)) { + throw new InvalidArgumentException('Cannot update "id" field.'); + } + } + $options = $this->inheritConnectionOptions($options); $wheres = $this->compileWheres(); - $result = $this->collection->updateMany($wheres, $query, $options); + $result = $this->collection->updateMany($wheres, $update, $options); if ($result->isAcknowledged()) { return $result->getModifiedCount() ? $result->getModifiedCount() : $result->getUpsertedCount(); } @@ -1540,7 +1554,7 @@ public function orWhereIntegerNotInRaw($column, $values, $boolean = 'and') throw new BadMethodCallException('This method is not supported by MongoDB'); } - private function renameId(array $values): array + private function aliasIdForQuery(array $values): array { if (isset($values['id'])) { $values['_id'] = $values['id']; @@ -1549,4 +1563,13 @@ private function renameId(array $values): array return $values; } + + private function aliasIdForResult(array $values): array + { + if (isset($values['_id'])) { + $values['id'] = $values['_id']; + } + + return $values; + } } From 6a5124f381df9fc732f3d8f2bf1691728cd7205c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=A9r=C3=B4me=20Tamarelle?= Date: Thu, 11 Jul 2024 17:32:17 +0200 Subject: [PATCH 06/10] Dont tuncate unused models --- tests/EmbeddedRelationsTest.php | 12 ------------ 1 file changed, 12 deletions(-) diff --git a/tests/EmbeddedRelationsTest.php b/tests/EmbeddedRelationsTest.php index 00a84360c..1fc68646c 100644 --- a/tests/EmbeddedRelationsTest.php +++ b/tests/EmbeddedRelationsTest.php @@ -10,12 +10,6 @@ use Mockery; use MongoDB\BSON\ObjectId; use MongoDB\Laravel\Tests\Models\Address; -use MongoDB\Laravel\Tests\Models\Book; -use MongoDB\Laravel\Tests\Models\Client; -use MongoDB\Laravel\Tests\Models\Group; -use MongoDB\Laravel\Tests\Models\Item; -use MongoDB\Laravel\Tests\Models\Photo; -use MongoDB\Laravel\Tests\Models\Role; use MongoDB\Laravel\Tests\Models\User; use function array_merge; @@ -27,12 +21,6 @@ public function tearDown(): void Mockery::close(); User::truncate(); - Book::truncate(); - Item::truncate(); - Role::truncate(); - Client::truncate(); - Group::truncate(); - Photo::truncate(); } public function testEmbedsManySave() From 533d1b7dc1db7248cf09c62af0f31f41f5b09ed3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=A9r=C3=B4me=20Tamarelle?= Date: Fri, 12 Jul 2024 01:10:45 +0200 Subject: [PATCH 07/10] V5 Query Builder return stdClass: https://github.com/laravel/framework/blob/213a370b703592587bafcd52d38a0ad772ff7442/src/Illuminate/Database/Connection.php#L118C16-L118C25 Alias id for _id everywhere Don't expose _id field: No _id attribute in Eloquent. Deprecate reading and writing _id attribute. Always convert datetime to UTCDateTime: https://github.com/laravel/framework/blob/213a370b703592587bafcd52d38a0ad772ff7442/src/Illuminate/Database/Connection.php#L733-L734 Timezone : using Carbon instead of system timezone. --- .../aggregation/AggregationsBuilderTest.php | 11 +- src/Auth/User.php | 1 - src/Collection.php | 1 + src/Eloquent/Builder.php | 2 +- src/Eloquent/DocumentModel.php | 14 +- src/Eloquent/Model.php | 7 - src/MongoDBQueueServiceProvider.php | 5 +- src/Query/AggregationBuilder.php | 2 +- src/Query/Builder.php | 96 +++-- src/Queue/Failed/MongoFailedJobProvider.php | 109 +---- src/Queue/MongoQueue.php | 7 +- src/Relations/EmbedsMany.php | 8 +- src/Relations/EmbedsOne.php | 4 +- src/Relations/EmbedsOneOrMany.php | 9 +- tests/AuthTest.php | 10 +- tests/Casts/DecimalTest.php | 2 +- tests/EmbeddedRelationsTest.php | 48 +-- tests/HybridRelationsTest.php | 24 +- tests/ModelTest.php | 109 ++--- tests/Models/Address.php | 1 - tests/Models/Birthday.php | 1 - tests/Models/Client.php | 1 - tests/Models/Experience.php | 1 - tests/Models/Group.php | 3 +- tests/Models/Guarded.php | 1 - tests/Models/HiddenAnimal.php | 1 - tests/Models/IdIsBinaryUuid.php | 3 +- tests/Models/IdIsInt.php | 3 +- tests/Models/IdIsString.php | 3 +- tests/Models/Item.php | 1 - tests/Models/Label.php | 1 - tests/Models/Location.php | 1 - tests/Models/Photo.php | 1 - tests/Models/Role.php | 1 - tests/Models/Scoped.php | 1 - tests/Models/Skill.php | 1 - tests/Models/Soft.php | 1 - tests/Models/User.php | 3 +- tests/Query/AggregationBuilderTest.php | 14 +- tests/Query/BuilderTest.php | 11 +- tests/QueryBuilderTest.php | 240 +++++------ tests/QueryTest.php | 2 +- .../Failed/MongoFailedJobProviderTest.php | 9 +- tests/QueueTest.php | 37 +- tests/RelationsTest.php | 386 +++++++++--------- tests/SchemaTest.php | 34 +- tests/SchemaVersionTest.php | 2 +- tests/Ticket/GH2783Test.php | 2 +- tests/TransactionTest.php | 26 +- 49 files changed, 585 insertions(+), 676 deletions(-) diff --git a/docs/includes/fundamentals/aggregation/AggregationsBuilderTest.php b/docs/includes/fundamentals/aggregation/AggregationsBuilderTest.php index 4880ee75f..fa8a43bf6 100644 --- a/docs/includes/fundamentals/aggregation/AggregationsBuilderTest.php +++ b/docs/includes/fundamentals/aggregation/AggregationsBuilderTest.php @@ -68,7 +68,7 @@ public function testAggregationBuilderSortStage(): void // end aggregation sort stage $this->assertEquals(6, $result->count()); - $this->assertEquals('Janet Doe', $result->first()['name']); + $this->assertEquals('Janet Doe', $result->first()->name); } public function testAggregationBuilderProjectStage(): void @@ -80,8 +80,9 @@ public function testAggregationBuilderProjectStage(): void // end aggregation project stage $this->assertEquals(6, $result->count()); - $this->assertNotNull($result->first()['name']); - $this->assertArrayNotHasKey('_id', $result->first()); + $this->assertNotNull($result->first()->name); + $this->assertObjectNotHasProperty('_id', $result->first()); + $this->assertObjectNotHasProperty('id', $result->first()); } public function testAggregationBuilderPipeline(): void @@ -104,7 +105,7 @@ public function testAggregationBuilderPipeline(): void $result = $pipeline->get(); $this->assertEquals(2, $result->count()); - $this->assertNotNull($result->first()['birth_year_avg']); + $this->assertNotNull($result->first()->birth_year_avg); } // phpcs:disable Squiz.Commenting.FunctionComment.WrongStyle @@ -130,6 +131,6 @@ public function testCustomOperatorFactory(): void $result = $pipeline->get(); $this->assertEquals(6, $result->count()); - $this->assertNotNull($result->first()['birth_year']); + $this->assertNotNull($result->first()->birth_year); } } diff --git a/src/Auth/User.php b/src/Auth/User.php index a58a898ad..e37fefd3c 100644 --- a/src/Auth/User.php +++ b/src/Auth/User.php @@ -11,6 +11,5 @@ class User extends BaseUser { use DocumentModel; - protected $primaryKey = '_id'; protected $keyType = 'string'; } diff --git a/src/Collection.php b/src/Collection.php index 22c0dfa05..e78fdea6e 100644 --- a/src/Collection.php +++ b/src/Collection.php @@ -6,6 +6,7 @@ use Exception; use MongoDB\BSON\ObjectID; +use MongoDB\BSON\UTCDateTime; use MongoDB\Collection as MongoCollection; use function array_walk_recursive; diff --git a/src/Eloquent/Builder.php b/src/Eloquent/Builder.php index da96b64f1..8bd80e49d 100644 --- a/src/Eloquent/Builder.php +++ b/src/Eloquent/Builder.php @@ -191,7 +191,7 @@ public function raw($value = null) } // The result is a single object. - if (is_array($results) && array_key_exists('_id', $results)) { + if (is_array($results) && array_key_exists('id', $results)) { return $this->model->newFromBuilder((array) $results); } diff --git a/src/Eloquent/DocumentModel.php b/src/Eloquent/DocumentModel.php index 15c33ef16..ecb5df561 100644 --- a/src/Eloquent/DocumentModel.php +++ b/src/Eloquent/DocumentModel.php @@ -76,8 +76,8 @@ public function getIdAttribute($value = null) { // If we don't have a value for 'id', we will use the MongoDB '_id' value. // This allows us to work with models in a more sql-like way. - if (! $value && array_key_exists('_id', $this->attributes)) { - $value = $this->attributes['_id']; + if (! $value && array_key_exists('id', $this->attributes)) { + $value = $this->attributes['id']; } // Convert ObjectID to string. @@ -238,8 +238,8 @@ public function setAttribute($key, $value) }; } - // Convert _id to ObjectID. - if ($key === '_id' && is_string($value)) { + // Convert "id" to ObjectID. + if ($key === 'id' && is_string($value)) { $builder = $this->newBaseQueryBuilder(); $value = $builder->convertKey($value); @@ -721,9 +721,9 @@ protected function isBSON(mixed $value): bool public function save(array $options = []) { // SQL databases would use autoincrement the id field if set to null. - // Apply the same behavior to MongoDB with _id only, otherwise null would be stored. - if (array_key_exists('_id', $this->attributes) && $this->attributes['_id'] === null) { - unset($this->attributes['_id']); + // Apply the same behavior to MongoDB with "id" only, otherwise null would be stored. + if (array_key_exists('id', $this->attributes) && $this->attributes['id'] === null) { + unset($this->attributes['id']); } $saved = parent::save($options); diff --git a/src/Eloquent/Model.php b/src/Eloquent/Model.php index fcb9c4f04..54eef1dc5 100644 --- a/src/Eloquent/Model.php +++ b/src/Eloquent/Model.php @@ -16,13 +16,6 @@ abstract class Model extends BaseModel { use DocumentModel; - /** - * The primary key for the model. - * - * @var string - */ - protected $primaryKey = '_id'; - /** * The primary key type. * diff --git a/src/MongoDBQueueServiceProvider.php b/src/MongoDBQueueServiceProvider.php index ea7a06176..1b7bf2ca3 100644 --- a/src/MongoDBQueueServiceProvider.php +++ b/src/MongoDBQueueServiceProvider.php @@ -4,6 +4,7 @@ namespace MongoDB\Laravel; +use Illuminate\Queue\Failed\DatabaseFailedJobProvider; use Illuminate\Queue\Failed\NullFailedJobProvider; use Illuminate\Queue\QueueServiceProvider; use MongoDB\Laravel\Queue\Failed\MongoFailedJobProvider; @@ -52,14 +53,14 @@ protected function registerFailedJobServices() /** * Create a new MongoDB failed job provider. */ - protected function mongoFailedJobProvider(array $config): MongoFailedJobProvider + protected function mongoFailedJobProvider(array $config): DatabaseFailedJobProvider { if (! isset($config['collection']) && isset($config['table'])) { trigger_error('Since mongodb/laravel-mongodb 4.4: Using "table" option for the queue is deprecated. Use "collection" instead.', E_USER_DEPRECATED); $config['collection'] = $config['table']; } - return new MongoFailedJobProvider( + return new DatabaseFailedJobProvider( $this->app['db'], $config['database'] ?? null, $config['collection'] ?? 'failed_jobs', diff --git a/src/Query/AggregationBuilder.php b/src/Query/AggregationBuilder.php index ad0c195d4..1017acc82 100644 --- a/src/Query/AggregationBuilder.php +++ b/src/Query/AggregationBuilder.php @@ -88,7 +88,7 @@ private function execute(array $options): CursorInterface&Iterator $pipeline = $encoder->encode($this->getPipeline()); $options = array_replace( - ['typeMap' => ['root' => 'array', 'document' => 'array']], + ['typeMap' => ['root' => 'object', 'document' => 'object']], $this->options, $options, ); diff --git a/src/Query/Builder.php b/src/Query/Builder.php index 65e6aa2c9..a8717f212 100644 --- a/src/Query/Builder.php +++ b/src/Query/Builder.php @@ -6,6 +6,7 @@ use ArgumentCountError; use BadMethodCallException; +use Carbon\CarbonImmutable; use Carbon\CarbonPeriod; use Closure; use DateTimeInterface; @@ -25,6 +26,7 @@ use MongoDB\Driver\Cursor; use Override; use RuntimeException; +use stdClass; use function array_fill_keys; use function array_is_list; @@ -39,6 +41,7 @@ use function call_user_func_array; use function count; use function ctype_xdigit; +use function date_default_timezone_get; use function dd; use function dump; use function end; @@ -46,6 +49,7 @@ use function func_get_args; use function func_num_args; use function get_debug_type; +use function get_object_vars; use function implode; use function in_array; use function is_array; @@ -53,6 +57,7 @@ use function is_callable; use function is_float; use function is_int; +use function is_object; use function is_string; use function md5; use function preg_match; @@ -227,7 +232,7 @@ public function hint($index) /** @inheritdoc */ public function find($id, $columns = []) { - return $this->where('_id', '=', $this->convertKey($id))->first($columns); + return $this->where('id', '=', $this->convertKey($id))->first($columns); } /** @inheritdoc */ @@ -391,7 +396,7 @@ public function toMql(): array } $options = [ - 'typeMap' => ['root' => 'array', 'document' => 'array'], + 'typeMap' => ['root' => 'object', 'document' => 'array'], ]; // Add custom query options @@ -451,7 +456,7 @@ public function toMql(): array } // Fix for legacy support, converts the results to arrays instead of objects. - $options['typeMap'] = ['root' => 'array', 'document' => 'array']; + $options['typeMap'] = ['root' => 'object', 'document' => 'array']; // Add custom query options if (count($this->options)) { @@ -506,7 +511,7 @@ public function getFresh($columns = [], $returnLazy = false) if ($returnLazy) { return LazyCollection::make(function () use ($result) { foreach ($result as $item) { - yield $this->aliasIdForResult($item); + yield is_object($item) ? $this->aliasIdForResult($item) : $item; } }); } @@ -515,8 +520,8 @@ public function getFresh($columns = [], $returnLazy = false) $result = $result->toArray(); } - foreach ($result as &$document) { - $document = $this->aliasIdForResult($document); + foreach ($result as &$item) { + $item = is_object($item) ? $this->aliasIdForResult($item) : $item; } return new Collection($result); @@ -590,7 +595,7 @@ public function aggregate($function = null, $columns = ['*']) if (isset($results[0])) { $result = (array) $results[0]; - return $result['aggregate']; + return $this->aliasIdForResult($result['aggregate']); } } @@ -628,6 +633,7 @@ public function orderBy($column, $direction = 'asc') } $column = (string) $column; + if ($column === 'natural') { $this->orders['$natural'] = $direction; } else { @@ -692,10 +698,9 @@ public function insert(array $values) if (isset($document['_id']) && $document['_id'] !== $document['id']) { throw new InvalidArgumentException('Cannot insert document with different "id" and "_id" values'); } - - $document['_id'] = $document['id']; - unset($document['id']); } + + $document = $this->aliasIdForQuery($document); } $options = $this->inheritConnectionOptions(); @@ -710,6 +715,8 @@ public function insertGetId(array $values, $sequence = null) { $options = $this->inheritConnectionOptions(); + $values = $this->aliasIdForQuery($values); + $result = $this->collection->insertOne($values, $options); if (! $result->isAcknowledged()) { @@ -735,13 +742,6 @@ public function update(array $values, array $options = []) unset($values[$key]); } - // Since "id" is an alias for "_id", we prevent updating it - foreach ($values as $fields) { - if (array_key_exists('id', $fields)) { - throw new InvalidArgumentException('Cannot update "id" field.'); - } - } - return $this->performUpdate($values, $options); } @@ -778,9 +778,9 @@ public function pluck($column, $key = null) $results = $this->get($key === null ? [$column] : [$column, $key]); // Convert ObjectID's to strings - if (((string) $key) === '_id') { + if (((string) $key) === 'id') { $results = $results->map(function ($item) { - $item['_id'] = (string) $item['_id']; + $item->id = (string) $item->id; return $item; }); @@ -798,13 +798,14 @@ public function delete($id = null) // the ID to allow developers to simply and quickly remove a single row // from their database without manually specifying the where clauses. if ($id !== null) { - $this->where('_id', '=', $id); + $this->where('id', '=', $id); } $wheres = $this->compileWheres(); $options = $this->inheritConnectionOptions(); - if (is_int($this->limit)) { + /** 1000 is a large value used by Laravel {@see DatabaseFailedJobProvider} */ + if (is_int($this->limit) && $this->limit !== 1000) { if ($this->limit !== 1) { throw new LogicException(sprintf('Delete limit can be 1 or null (unlimited). Got %d', $this->limit)); } @@ -997,15 +998,19 @@ protected function performUpdate(array $update, array $options = []) } // Since "id" is an alias for "_id", we prevent updating it - foreach ($update as $operator => $fields) { + foreach ($update as &$fields) { if (array_key_exists('id', $fields)) { throw new InvalidArgumentException('Cannot update "id" field.'); } + + // Rename "id" to "_id" for embedded documents + $fields = $this->aliasIdForQuery($fields); } $options = $this->inheritConnectionOptions($options); $wheres = $this->compileWheres(); + $result = $this->collection->updateMany($wheres, $update, $options); if ($result->isAcknowledged()) { return $result->getModifiedCount() ? $result->getModifiedCount() : $result->getUpsertedCount(); @@ -1188,7 +1193,7 @@ protected function compileWheres(): array } } - return $compiled; + return $this->aliasIdForQuery($compiled); } protected function compileWhereBasic(array $where): array @@ -1561,13 +1566,52 @@ private function aliasIdForQuery(array $values): array unset($values['id']); } + foreach ($values as $key => $value) { + if (is_string($key) && str_ends_with($key, '.id')) { + $values[substr($key, 0, -3) . '._id'] = $value; + unset($values[$key]); + } + } + + foreach ($values as &$value) { + if ($value instanceof DateTimeInterface) { + $value = new UTCDateTime($value); + } elseif (is_array($value)) { + $value = $this->aliasIdForQuery($value); + } + } + return $values; } - private function aliasIdForResult(array $values): array + private function aliasIdForResult(stdClass|array $values): stdClass|array { - if (isset($values['_id'])) { - $values['id'] = $values['_id']; + if (is_array($values)) { + if (isset($values['_id'])) { + $values['id'] = $values['_id']; + unset($values['_id']); + } + + foreach ($values as $key => $value) { + if ($value instanceof UTCDateTime) { + $values[$key] = CarbonImmutable::createFromTimestamp($value->toDateTime()->getTimestamp(), 'UTC')->setTimezone(date_default_timezone_get()); + } elseif (is_array($value) || $value instanceof stdClass) { + $values[$key] = $this->aliasIdForResult($value); + } + } + } else { + if (isset($values->_id)) { + $values->id = $values->_id; + unset($values->_id); + } + + foreach (get_object_vars($values) as $key => $value) { + if ($value instanceof UTCDateTime) { + $values->{$key} = CarbonImmutable::createFromTimestamp($value->toDateTime()->getTimestamp(), 'UTC')->setTimezone(date_default_timezone_get()); + } elseif (is_array($value) || $value instanceof stdClass) { + $values->{$key} = $this->aliasIdForResult($value); + } + } } return $values; diff --git a/src/Queue/Failed/MongoFailedJobProvider.php b/src/Queue/Failed/MongoFailedJobProvider.php index 357f27ddc..f130036ce 100644 --- a/src/Queue/Failed/MongoFailedJobProvider.php +++ b/src/Queue/Failed/MongoFailedJobProvider.php @@ -4,116 +4,9 @@ namespace MongoDB\Laravel\Queue\Failed; -use Carbon\Carbon; -use DateTimeInterface; -use Exception; use Illuminate\Queue\Failed\DatabaseFailedJobProvider; -use MongoDB\BSON\ObjectId; -use MongoDB\BSON\UTCDateTime; - -use function array_map; +/** @deprecated Use {@see DatabaseFailedJobProvider} */ class MongoFailedJobProvider extends DatabaseFailedJobProvider { - /** - * Log a failed job into storage. - * - * @param string $connection - * @param string $queue - * @param string $payload - * @param Exception $exception - * - * @return void - */ - public function log($connection, $queue, $payload, $exception) - { - $this->getTable()->insert([ - 'connection' => $connection, - 'queue' => $queue, - 'payload' => $payload, - 'failed_at' => new UTCDateTime(Carbon::now()), - 'exception' => (string) $exception, - ]); - } - - /** - * Get a list of all of the failed jobs. - * - * @return object[] - */ - public function all() - { - $all = $this->getTable()->orderBy('_id', 'desc')->get()->all(); - - $all = array_map(function ($job) { - $job['id'] = (string) $job['_id']; - - return (object) $job; - }, $all); - - return $all; - } - - /** - * Get a single failed job. - * - * @param string $id - * - * @return object|null - */ - public function find($id) - { - $job = $this->getTable()->find($id); - - if (! $job) { - return null; - } - - $job['id'] = (string) $job['_id']; - - return (object) $job; - } - - /** - * Delete a single failed job from storage. - * - * @param string $id - * - * @return bool - */ - public function forget($id) - { - return $this->getTable()->where('_id', $id)->delete() > 0; - } - - /** - * Get the IDs of all the failed jobs. - * - * @param string|null $queue - * - * @return list - */ - public function ids($queue = null) - { - return $this->getTable() - ->when($queue !== null, static fn ($query) => $query->where('queue', $queue)) - ->orderBy('_id', 'desc') - ->pluck('_id') - ->all(); - } - - /** - * Prune all failed jobs older than the given date. - * - * @param DateTimeInterface $before - * - * @return int - */ - public function prune(DateTimeInterface $before) - { - return $this - ->getTable() - ->where('failed_at', '<', $before) - ->delete(); - } } diff --git a/src/Queue/MongoQueue.php b/src/Queue/MongoQueue.php index eeac36c78..5769bad9e 100644 --- a/src/Queue/MongoQueue.php +++ b/src/Queue/MongoQueue.php @@ -93,6 +93,7 @@ protected function getNextAvailableJobAndReserve($queue) if ($job) { $job->id = $job->_id; + unset($job->_id); } return $job; @@ -116,7 +117,7 @@ protected function releaseJobsThatHaveBeenReservedTooLong($queue) ->get(); foreach ($reserved as $job) { - $this->releaseJob($job['_id'], $job['attempts']); + $this->releaseJob($job->id, $job->attempts); } } @@ -130,7 +131,7 @@ protected function releaseJobsThatHaveBeenReservedTooLong($queue) */ protected function releaseJob($id, $attempts) { - $this->database->table($this->table)->where('_id', $id)->update([ + $this->database->table($this->table)->where('id', $id)->update([ 'reserved' => 0, 'reserved_at' => null, 'attempts' => $attempts, @@ -140,7 +141,7 @@ protected function releaseJob($id, $attempts) /** @inheritdoc */ public function deleteReserved($queue, $id) { - $this->database->collection($this->table)->where('_id', $id)->delete(); + $this->database->collection($this->table)->where('id', $id)->delete(); } /** @inheritdoc */ diff --git a/src/Relations/EmbedsMany.php b/src/Relations/EmbedsMany.php index 72c77b598..388e3ee3f 100644 --- a/src/Relations/EmbedsMany.php +++ b/src/Relations/EmbedsMany.php @@ -47,8 +47,8 @@ public function getResults() public function performInsert(Model $model) { // Generate a new key if needed. - if ($model->getKeyName() === '_id' && ! $model->getKey()) { - $model->setAttribute('_id', new ObjectID()); + if ($model->getKeyName() === 'id' && ! $model->getKey()) { + $model->setAttribute('id', new ObjectID()); } // For deeply nested documents, let the parent handle the changes. @@ -249,8 +249,8 @@ public function attach(Model $model) protected function associateNew($model) { // Create a new key if needed. - if ($model->getKeyName() === '_id' && ! $model->getAttribute('_id')) { - $model->setAttribute('_id', new ObjectID()); + if ($model->getKeyName() === 'id' && ! $model->getAttribute('id')) { + $model->setAttribute('id', new ObjectID()); } $records = $this->getEmbedded(); diff --git a/src/Relations/EmbedsOne.php b/src/Relations/EmbedsOne.php index 678141cf1..473133c0f 100644 --- a/src/Relations/EmbedsOne.php +++ b/src/Relations/EmbedsOne.php @@ -43,8 +43,8 @@ public function getEager() public function performInsert(Model $model) { // Generate a new key if needed. - if ($model->getKeyName() === '_id' && ! $model->getKey()) { - $model->setAttribute('_id', new ObjectID()); + if ($model->getKeyName() === 'id' && ! $model->getKey()) { + $model->setAttribute('id', new ObjectID()); } // For deeply nested documents, let the parent handle the changes. diff --git a/src/Relations/EmbedsOneOrMany.php b/src/Relations/EmbedsOneOrMany.php index 9c83aa299..4cee905ed 100644 --- a/src/Relations/EmbedsOneOrMany.php +++ b/src/Relations/EmbedsOneOrMany.php @@ -17,6 +17,7 @@ use function array_merge; use function count; use function is_array; +use function sprintf; use function throw_if; abstract class EmbedsOneOrMany extends Relation @@ -132,6 +133,10 @@ public function count($columns = '*'): int */ public function save(Model $model) { + if (! \MongoDB\Laravel\Eloquent\Model::isDocumentModel($model)) { + throw new LogicException(sprintf('Model "%s" must be a Document Model to be embedded.', $model::class)); + } + $model->setParentRelation($this); return $model->save() ? $model : false; @@ -214,17 +219,15 @@ protected function getIdsArrayFrom($ids) return $ids; } - /** @inheritdoc */ protected function getEmbedded() { // Get raw attributes to skip relations and accessors. $attributes = $this->parent->getAttributes(); // Get embedded models form parent attributes. - return isset($attributes[$this->localKey]) ? (array) $attributes[$this->localKey] : null; + return $attributes[$this->localKey] ?? null; } - /** @inheritdoc */ protected function setEmbedded($records) { // Assign models to parent attributes array. diff --git a/tests/AuthTest.php b/tests/AuthTest.php index eadb9b1f4..4f304767f 100644 --- a/tests/AuthTest.php +++ b/tests/AuthTest.php @@ -4,11 +4,11 @@ namespace MongoDB\Laravel\Tests; +use DateTimeInterface; use Illuminate\Auth\Passwords\PasswordBroker; use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Hash; -use MongoDB\BSON\UTCDateTime; use MongoDB\Laravel\Tests\Models\User; use function bcrypt; @@ -52,7 +52,7 @@ public function testRemindOld() $broker->sendResetLink( ['email' => 'john.doe@example.com'], function ($actualUser, $actualToken) use ($user, &$token) { - $this->assertEquals($user->_id, $actualUser->_id); + $this->assertEquals($user->id, $actualUser->id); // Store token for later use $token = $actualToken; }, @@ -61,9 +61,9 @@ function ($actualUser, $actualToken) use ($user, &$token) { $this->assertEquals(1, DB::collection('password_reset_tokens')->count()); $reminder = DB::collection('password_reset_tokens')->first(); - $this->assertEquals('john.doe@example.com', $reminder['email']); - $this->assertNotNull($reminder['token']); - $this->assertInstanceOf(UTCDateTime::class, $reminder['created_at']); + $this->assertEquals('john.doe@example.com', $reminder->email); + $this->assertNotNull($reminder->token); + $this->assertInstanceOf(DateTimeInterface::class, $reminder->created_at); $credentials = [ 'email' => 'john.doe@example.com', diff --git a/tests/Casts/DecimalTest.php b/tests/Casts/DecimalTest.php index f69d24d62..e4e5ced7f 100644 --- a/tests/Casts/DecimalTest.php +++ b/tests/Casts/DecimalTest.php @@ -120,7 +120,7 @@ private function setBSONType($value, $id = null) return Casting::raw(function (Collection $collection) use ($id, $value) { if (! empty($id)) { return $collection->updateOne( - ['_id' => $id], + ['id' => $id], ['$set' => ['decimalNumber' => $value]], ); } diff --git a/tests/EmbeddedRelationsTest.php b/tests/EmbeddedRelationsTest.php index 1fc68646c..836e0dfca 100644 --- a/tests/EmbeddedRelationsTest.php +++ b/tests/EmbeddedRelationsTest.php @@ -49,15 +49,15 @@ public function testEmbedsManySave() $this->assertEquals(['London'], $user->addresses->pluck('city')->all()); $this->assertInstanceOf(DateTime::class, $address->created_at); $this->assertInstanceOf(DateTime::class, $address->updated_at); - $this->assertNotNull($address->_id); - $this->assertIsString($address->_id); + $this->assertNotNull($address->id); + $this->assertIsString($address->id); $raw = $address->getAttributes(); - $this->assertInstanceOf(ObjectId::class, $raw['_id']); + $this->assertInstanceOf(ObjectId::class, $raw['id']); $address = $user->addresses()->save(new Address(['city' => 'Paris'])); - $user = User::find($user->_id); + $user = User::find($user->id); $this->assertEquals(['London', 'Paris'], $user->addresses->pluck('city')->all()); $address->setEventDispatcher($events = Mockery::mock(Dispatcher::class)); @@ -83,7 +83,7 @@ public function testEmbedsManySave() $this->assertEquals(2, $user->addresses()->count()); $this->assertEquals(['London', 'New York'], $user->addresses->pluck('city')->all()); - $freshUser = User::find($user->_id); + $freshUser = User::find($user->id); $this->assertEquals(['London', 'New York'], $freshUser->addresses->pluck('city')->all()); $address = $user->addresses->first(); @@ -93,7 +93,7 @@ public function testEmbedsManySave() $this->assertInstanceOf(User::class, $address->user); $this->assertEmpty($address->relationsToArray()); // prevent infinite loop - $user = User::find($user->_id); + $user = User::find($user->id); $user->addresses()->save(new Address(['city' => 'Bruxelles'])); $this->assertEquals(['London', 'New York', 'Bruxelles'], $user->addresses->pluck('city')->all()); @@ -102,7 +102,7 @@ public function testEmbedsManySave() $user->addresses()->save($address); $this->assertEquals(['London', 'Manhattan', 'Bruxelles'], $user->addresses->pluck('city')->all()); - $freshUser = User::find($user->_id); + $freshUser = User::find($user->id); $this->assertEquals(['London', 'Manhattan', 'Bruxelles'], $freshUser->addresses->pluck('city')->all()); } @@ -123,16 +123,16 @@ public function testEmbedsManyAssociate() $user->addresses()->associate($address); $this->assertEquals(['London'], $user->addresses->pluck('city')->all()); - $this->assertNotNull($address->_id); + $this->assertNotNull($address->id); - $freshUser = User::find($user->_id); + $freshUser = User::find($user->id); $this->assertEquals([], $freshUser->addresses->pluck('city')->all()); $address->city = 'Londinium'; $user->addresses()->associate($address); $this->assertEquals(['Londinium'], $user->addresses->pluck('city')->all()); - $freshUser = User::find($user->_id); + $freshUser = User::find($user->id); $this->assertEquals([], $freshUser->addresses->pluck('city')->all()); } @@ -163,7 +163,7 @@ public function testEmbedsManyDuplicate() $this->assertEquals(1, $user->addresses->count()); $this->assertEquals(['Paris'], $user->addresses->pluck('city')->all()); - $user->addresses()->create(['_id' => $address->_id, 'city' => 'Bruxelles']); + $user->addresses()->create(['id' => $address->id, 'city' => 'Bruxelles']); $this->assertEquals(1, $user->addresses->count()); $this->assertEquals(['Bruxelles'], $user->addresses->pluck('city')->all()); } @@ -173,21 +173,21 @@ public function testEmbedsManyCreate() $user = User::create([]); $address = $user->addresses()->create(['city' => 'Bruxelles']); $this->assertInstanceOf(Address::class, $address); - $this->assertIsString($address->_id); + $this->assertIsString($address->id); $this->assertEquals(['Bruxelles'], $user->addresses->pluck('city')->all()); $raw = $address->getAttributes(); - $this->assertInstanceOf(ObjectId::class, $raw['_id']); + $this->assertInstanceOf(ObjectId::class, $raw['id']); $freshUser = User::find($user->id); $this->assertEquals(['Bruxelles'], $freshUser->addresses->pluck('city')->all()); $user = User::create([]); - $address = $user->addresses()->create(['_id' => '', 'city' => 'Bruxelles']); - $this->assertIsString($address->_id); + $address = $user->addresses()->create(['id' => '', 'city' => 'Bruxelles']); + $this->assertIsString($address->id); $raw = $address->getAttributes(); - $this->assertInstanceOf(ObjectId::class, $raw['_id']); + $this->assertInstanceOf(ObjectId::class, $raw['id']); } public function testEmbedsManyCreateMany() @@ -223,7 +223,7 @@ public function testEmbedsManyDestroy() ->once() ->with('eloquent.deleted: ' . $address::class, Mockery::type(Address::class)); - $user->addresses()->destroy($address->_id); + $user->addresses()->destroy($address->id); $this->assertEquals(['Bristol', 'Bruxelles'], $user->addresses->pluck('city')->all()); $address->unsetEventDispatcher(); @@ -238,7 +238,7 @@ public function testEmbedsManyDestroy() $freshUser = User::find($user->id); $this->assertEquals(['Bruxelles', 'Paris', 'San Francisco'], $freshUser->addresses->pluck('city')->all()); - $ids = $user->addresses->pluck('_id'); + $ids = $user->addresses->pluck('id'); $user->addresses()->destroy($ids); $this->assertEquals([], $user->addresses->pluck('city')->all()); @@ -415,13 +415,13 @@ public function testEmbedsManyFindOrContains() $address1 = $user->addresses()->save(new Address(['city' => 'New York'])); $address2 = $user->addresses()->save(new Address(['city' => 'Paris'])); - $address = $user->addresses()->find($address1->_id); + $address = $user->addresses()->find($address1->id); $this->assertEquals($address->city, $address1->city); - $address = $user->addresses()->find($address2->_id); + $address = $user->addresses()->find($address2->id); $this->assertEquals($address->city, $address2->city); - $this->assertTrue($user->addresses()->contains($address2->_id)); + $this->assertTrue($user->addresses()->contains($address2->id)); $this->assertFalse($user->addresses()->contains('123')); } @@ -553,11 +553,11 @@ public function testEmbedsOne() $this->assertEquals('Mark Doe', $user->father->name); $this->assertInstanceOf(DateTime::class, $father->created_at); $this->assertInstanceOf(DateTime::class, $father->updated_at); - $this->assertNotNull($father->_id); - $this->assertIsString($father->_id); + $this->assertNotNull($father->id); + $this->assertIsString($father->id); $raw = $father->getAttributes(); - $this->assertInstanceOf(ObjectId::class, $raw['_id']); + $this->assertInstanceOf(ObjectId::class, $raw['id']); $father->setEventDispatcher($events = Mockery::mock(Dispatcher::class)); $events->shouldReceive('dispatch')->with('eloquent.retrieved: ' . $father::class, Mockery::any()); diff --git a/tests/HybridRelationsTest.php b/tests/HybridRelationsTest.php index 5253784c9..71958d27d 100644 --- a/tests/HybridRelationsTest.php +++ b/tests/HybridRelationsTest.php @@ -83,7 +83,7 @@ public function testSqlRelations() // MongoDB has many $book = new SqlBook(['title' => 'Game of Thrones']); $user->sqlBooks()->save($book); - $user = User::find($user->_id); // refetch + $user = User::find($user->id); // refetch $this->assertCount(1, $user->sqlBooks); // SQL belongs to @@ -93,7 +93,7 @@ public function testSqlRelations() // MongoDB has one $role = new SqlRole(['type' => 'admin']); $user->sqlRole()->save($role); - $user = User::find($user->_id); // refetch + $user = User::find($user->id); // refetch $this->assertEquals('admin', $user->sqlRole->type); // SQL belongs to @@ -239,16 +239,16 @@ public function testHybridBelongsToMany() // sync (pivot is empty) $skill->sqlUsers()->sync([$user->id, $user2->id]); - $check = Skill::query()->find($skill->_id); + $check = Skill::query()->find($skill->id); $this->assertEquals(2, $check->sqlUsers->count()); // sync (pivot is not empty) $skill->sqlUsers()->sync($user); - $check = Skill::query()->find($skill->_id); + $check = Skill::query()->find($skill->id); $this->assertEquals(1, $check->sqlUsers->count()); // Inverse sync (pivot is empty) - $user->skills()->sync([$skill->_id, $skill2->_id]); + $user->skills()->sync([$skill->id, $skill2->id]); $check = SqlUser::find($user->id); $this->assertEquals(2, $check->skills->count()); @@ -288,7 +288,7 @@ public function testHybridMorphToManySqlModelToMongoModel() $label2 = Label::query()->create(['name' => 'MongoDB']); // MorphToMany (pivot is empty) - $user->labels()->sync([$label->_id, $label2->_id]); + $user->labels()->sync([$label->id, $label2->id]); $check = SqlUser::query()->find($user->id); $this->assertEquals(2, $check->labels->count()); @@ -308,12 +308,12 @@ public function testHybridMorphToManySqlModelToMongoModel() // Inverse MorphToMany (pivot is empty) $label->sqlUsers()->sync([$user->id, $user2->id]); - $check = Label::query()->find($label->_id); + $check = Label::query()->find($label->id); $this->assertEquals(2, $check->sqlUsers->count()); // Inverse MorphToMany (pivot is empty) $label->sqlUsers()->sync([$user->id, $user2->id]); - $check = Label::query()->find($label->_id); + $check = Label::query()->find($label->id); $this->assertEquals(2, $check->sqlUsers->count()); } @@ -340,21 +340,21 @@ public function testHybridMorphToManyMongoModelToSqlModel() // MorphToMany (pivot is empty) $experience->sqlUsers()->sync([$user->id, $user2->id]); - $check = Experience::query()->find($experience->_id); + $check = Experience::query()->find($experience->id); $this->assertEquals(2, $check->sqlUsers->count()); // MorphToMany (pivot is not empty) $experience->sqlUsers()->sync([$user->id]); - $check = Experience::query()->find($experience->_id); + $check = Experience::query()->find($experience->id); $this->assertEquals(1, $check->sqlUsers->count()); // Inverse MorphToMany (pivot is empty) - $user->experiences()->sync([$experience->_id, $experience2->_id]); + $user->experiences()->sync([$experience->id, $experience2->id]); $check = SqlUser::query()->find($user->id); $this->assertEquals(2, $check->experiences->count()); // Inverse MorphToMany (pivot is not empty) - $user->experiences()->sync([$experience->_id]); + $user->experiences()->sync([$experience->id]); $check = SqlUser::query()->find($user->id); $this->assertEquals(1, $check->experiences->count()); diff --git a/tests/ModelTest.php b/tests/ModelTest.php index 3c4cbd8df..25203c622 100644 --- a/tests/ModelTest.php +++ b/tests/ModelTest.php @@ -63,7 +63,7 @@ public function testNewModel(): void $this->assertInstanceOf(Connection::class, $user->getConnection()); $this->assertFalse($user->exists); $this->assertEquals('users', $user->getTable()); - $this->assertEquals('_id', $user->getKeyName()); + $this->assertEquals('id', $user->getKeyName()); } public function testQualifyColumn(): void @@ -89,14 +89,14 @@ public function testInsert(): void $this->assertTrue($user->exists); $this->assertEquals(1, User::count()); - $this->assertTrue(isset($user->_id)); - $this->assertIsString($user->_id); - $this->assertNotEquals('', (string) $user->_id); - $this->assertNotEquals(0, strlen((string) $user->_id)); + $this->assertTrue(isset($user->id)); + $this->assertIsString($user->id); + $this->assertNotEquals('', (string) $user->id); + $this->assertNotEquals(0, strlen((string) $user->id)); $this->assertInstanceOf(Carbon::class, $user->created_at); $raw = $user->getAttributes(); - $this->assertInstanceOf(ObjectID::class, $raw['_id']); + $this->assertInstanceOf(ObjectID::class, $raw['id']); $this->assertEquals('John Doe', $user->name); $this->assertEquals(35, $user->age); @@ -111,9 +111,9 @@ public function testUpdate(): void $user->save(); $raw = $user->getAttributes(); - $this->assertInstanceOf(ObjectID::class, $raw['_id']); + $this->assertInstanceOf(ObjectID::class, $raw['id']); - $check = User::find($user->_id); + $check = User::find($user->id); $this->assertInstanceOf(User::class, $check); $check->age = 36; $check->save(); @@ -129,16 +129,16 @@ public function testUpdate(): void $user->update(['age' => 20]); $raw = $user->getAttributes(); - $this->assertInstanceOf(ObjectID::class, $raw['_id']); + $this->assertInstanceOf(ObjectID::class, $raw['id']); - $check = User::find($user->_id); + $check = User::find($user->id); $this->assertEquals(20, $check->age); $check->age = 24; $check->fullname = 'Hans Thomas'; // new field $check->save(); - $check = User::find($user->_id); + $check = User::find($user->id); $this->assertEquals(24, $check->age); $this->assertEquals('Hans Thomas', $check->fullname); } @@ -146,46 +146,46 @@ public function testUpdate(): void public function testManualStringId(): void { $user = new User(); - $user->_id = '4af9f23d8ead0e1d32000000'; + $user->id = '4af9f23d8ead0e1d32000000'; $user->name = 'John Doe'; $user->title = 'admin'; $user->age = 35; $user->save(); $this->assertTrue($user->exists); - $this->assertEquals('4af9f23d8ead0e1d32000000', $user->_id); + $this->assertEquals('4af9f23d8ead0e1d32000000', $user->id); $raw = $user->getAttributes(); - $this->assertInstanceOf(ObjectID::class, $raw['_id']); + $this->assertInstanceOf(ObjectID::class, $raw['id']); $user = new User(); - $user->_id = 'customId'; + $user->id = 'customId'; $user->name = 'John Doe'; $user->title = 'admin'; $user->age = 35; $user->save(); $this->assertTrue($user->exists); - $this->assertEquals('customId', $user->_id); + $this->assertEquals('customId', $user->id); $raw = $user->getAttributes(); - $this->assertIsString($raw['_id']); + $this->assertIsString($raw['id']); } public function testManualIntId(): void { $user = new User(); - $user->_id = 1; + $user->id = 1; $user->name = 'John Doe'; $user->title = 'admin'; $user->age = 35; $user->save(); $this->assertTrue($user->exists); - $this->assertEquals(1, $user->_id); + $this->assertEquals(1, $user->id); $raw = $user->getAttributes(); - $this->assertIsInt($raw['_id']); + $this->assertIsInt($raw['id']); } public function testDelete(): void @@ -233,11 +233,11 @@ public function testFind(): void $user->age = 35; $user->save(); - $check = User::find($user->_id); + $check = User::find($user->id); $this->assertInstanceOf(User::class, $check); $this->assertTrue(Model::isDocumentModel($check)); $this->assertTrue($check->exists); - $this->assertEquals($user->_id, $check->_id); + $this->assertEquals($user->id, $check->id); $this->assertEquals('John Doe', $check->name); $this->assertEquals(35, $check->age); @@ -305,7 +305,7 @@ public function testCreate(): void $check = User::where('name', 'Jane Poe')->first(); $this->assertInstanceOf(User::class, $check); - $this->assertEquals($user->_id, $check->_id); + $this->assertEquals($user->id, $check->id); } public function testDestroy(): void @@ -316,7 +316,7 @@ public function testDestroy(): void $user->age = 35; $user->save(); - User::destroy((string) $user->_id); + User::destroy((string) $user->id); $this->assertEquals(0, User::count()); } @@ -333,7 +333,7 @@ public function testTouch(): void sleep(1); $user->touch(); - $check = User::find($user->_id); + $check = User::find($user->id); $this->assertInstanceOf(User::class, $check); $this->assertNotEquals($old, $check->updated_at); @@ -371,6 +371,7 @@ public function testSoftDelete(): void $this->assertEquals(2, Soft::count()); } + /** @param class-string $model */ #[DataProvider('provideId')] public function testPrimaryKey(string $model, $id, $expected, bool $expectedFound): void { @@ -378,12 +379,12 @@ public function testPrimaryKey(string $model, $id, $expected, bool $expectedFoun $expectedType = get_debug_type($expected); $document = new $model(); - $this->assertEquals('_id', $document->getKeyName()); + $this->assertEquals('id', $document->getKeyName()); - $document->_id = $id; + $document->id = $id; $document->save(); - $this->assertSame($expectedType, get_debug_type($document->_id)); - $this->assertEquals($expected, $document->_id); + $this->assertSame($expectedType, get_debug_type($document->id)); + $this->assertEquals($expected, $document->id); $this->assertSame($expectedType, get_debug_type($document->getKey())); $this->assertEquals($expected, $document->getKey()); @@ -391,8 +392,8 @@ public function testPrimaryKey(string $model, $id, $expected, bool $expectedFoun if ($expectedFound) { $this->assertNotNull($check, 'Not found'); - $this->assertSame($expectedType, get_debug_type($check->_id)); - $this->assertEquals($id, $check->_id); + $this->assertSame($expectedType, get_debug_type($check->id)); + $this->assertEquals($id, $check->id); $this->assertSame($expectedType, get_debug_type($check->getKey())); $this->assertEquals($id, $check->getKey()); } else { @@ -500,10 +501,10 @@ public function testToArray(): void $array = $item->toArray(); $keys = array_keys($array); sort($keys); - $this->assertEquals(['_id', 'created_at', 'name', 'type', 'updated_at'], $keys); + $this->assertEquals(['created_at', 'id', 'name', 'type', 'updated_at'], $keys); $this->assertIsString($array['created_at']); $this->assertIsString($array['updated_at']); - $this->assertIsString($array['_id']); + $this->assertIsString($array['id']); } public function testUnset(): void @@ -525,8 +526,8 @@ public function testUnset(): void $this->assertTrue(isset($user2->note2)); // Re-fetch to be sure - $user1 = User::find($user1->_id); - $user2 = User::find($user2->_id); + $user1 = User::find($user1->id); + $user2 = User::find($user2->id); $this->assertFalse(isset($user1->note1)); $this->assertTrue(isset($user1->note2)); @@ -540,7 +541,7 @@ public function testUnset(): void $this->assertFalse(isset($user2->note2)); // Re-re-fetch to be sure - $user2 = User::find($user2->_id); + $user2 = User::find($user2->id); $this->assertFalse(isset($user2->note1)); $this->assertFalse(isset($user2->note2)); @@ -588,14 +589,14 @@ public function testUnsetAndSet(): void $this->assertSame(['note1' => 'GHI'], $user->getDirty()); // Fetch to be sure the changes are not persisted yet - $userCheck = User::find($user->_id); + $userCheck = User::find($user->id); $this->assertSame('ABC', $userCheck['note1']); // Persist the changes $user->save(); // Re-fetch to be sure - $user = User::find($user->_id); + $user = User::find($user->id); $this->assertTrue(isset($user->note1)); $this->assertSame('GHI', $user->note1); @@ -622,7 +623,7 @@ public function testUnsetDotAttributes(): void $this->assertTrue(isset($user->notes['note2'])); // Re-fetch to be sure - $user = User::find($user->_id); + $user = User::find($user->id); $this->assertFalse(isset($user->notes['note1'])); $this->assertTrue(isset($user->notes['note2'])); @@ -639,7 +640,7 @@ public function testUnsetDotAttributes(): void $this->assertFalse(isset($user->notes)); // Re-fetch to be sure - $user = User::find($user->_id); + $user = User::find($user->id); $this->assertFalse(isset($user->notes)); } @@ -671,7 +672,7 @@ public function testUnsetDotAttributesAndSet(): void $this->assertSame(['note2' => 'DEF', 'note1' => 'ABC'], $user->notes); // Re-fetch to be sure - $user = User::find($user->_id); + $user = User::find($user->id); $this->assertSame(['note2' => 'DEF', 'note1' => 'ABC'], $user->notes); } @@ -688,14 +689,14 @@ public function testDateUseLocalTimeZone(): void $this->assertEquals($tz, $user->birthday->getTimezone()->getName()); $user->save(); - $user = User::find($user->_id); + $user = User::find($user->id); $this->assertEquals($date, $user->birthday); $this->assertEquals($tz, $user->birthday->getTimezone()->getName()); $this->assertSame('1965-03-02T15:30:10+10:00', $user->birthday->format(DATE_ATOM)); $tz = 'America/New_York'; date_default_timezone_set($tz); - $user = User::find($user->_id); + $user = User::find($user->id); $this->assertEquals($date, $user->birthday); $this->assertEquals($tz, $user->birthday->getTimezone()->getName()); $this->assertSame('1965-03-02T00:30:10-05:00', $user->birthday->format(DATE_ATOM)); @@ -714,7 +715,7 @@ public function testDates(): void $user = User::create(['name' => 'John Doe', 'birthday' => new DateTime('1980/1/1')]); $this->assertInstanceOf(Carbon::class, $user->birthday); - $check = User::find($user->_id); + $check = User::find($user->id); $this->assertInstanceOf(Carbon::class, $check->birthday); $this->assertEquals($user->birthday, $check->birthday); @@ -799,7 +800,7 @@ public function testDateNull(): void $user->save(); // Re-fetch to be sure - $user = User::find($user->_id); + $user = User::find($user->id); $this->assertNull($user->birthday); // Nested field with dot notation @@ -811,7 +812,7 @@ public function testDateNull(): void $this->assertNull($user->getAttribute('entry.date')); // Re-fetch to be sure - $user = User::find($user->_id); + $user = User::find($user->id); $this->assertNull($user->getAttribute('entry.date')); } @@ -829,10 +830,10 @@ public function testIdAttribute(): void { $user = User::create(['name' => 'John Doe']); $this->assertInstanceOf(User::class, $user); - $this->assertEquals($user->id, $user->_id); + $this->assertSame($user->id, $user->_id); $user = User::create(['id' => 'custom_id', 'name' => 'John Doe']); - $this->assertNotEquals($user->id, $user->_id); + $this->assertSame($user->id, $user->_id); } public function testPushPull(): void @@ -845,20 +846,20 @@ public function testPushPull(): void $user->push('tags', 'tag2', true); $this->assertEquals(['tag1', 'tag1', 'tag2'], $user->tags); - $user = User::where('_id', $user->_id)->first(); + $user = User::where('id', $user->id)->first(); $this->assertEquals(['tag1', 'tag1', 'tag2'], $user->tags); $user->pull('tags', 'tag1'); $this->assertEquals(['tag2'], $user->tags); - $user = User::where('_id', $user->_id)->first(); + $user = User::where('id', $user->id)->first(); $this->assertEquals(['tag2'], $user->tags); $user->push('tags', 'tag3'); $user->pull('tags', ['tag2', 'tag3']); $this->assertEquals([], $user->tags); - $user = User::where('_id', $user->_id)->first(); + $user = User::where('id', $user->id)->first(); $this->assertEquals([], $user->tags); } @@ -1014,7 +1015,7 @@ public function testFirstOrCreate(): void $check = User::where('name', $name)->first(); $this->assertInstanceOf(User::class, $check); - $this->assertEquals($user->_id, $check->_id); + $this->assertEquals($user->id, $check->id); } public function testEnumCast(): void @@ -1128,7 +1129,7 @@ public function testCreateOrFirst(bool $transaction) } } - #[TestWith([['_id' => new ObjectID()]])] + #[TestWith([['id' => new ObjectID()]])] #[TestWith([['foo' => 'bar']])] public function testUpdateOrCreate(array $criteria) { @@ -1183,7 +1184,7 @@ public function testUpdateOrCreate(array $criteria) public function testCreateWithNullId() { - $user = User::create(['_id' => null, 'email' => 'foo@bar']); + $user = User::create(['id' => null, 'email' => 'foo@bar']); $this->assertNotNull(ObjectId::class, $user->id); $this->assertSame(1, User::count()); } diff --git a/tests/Models/Address.php b/tests/Models/Address.php index d94e31d24..60e4d6431 100644 --- a/tests/Models/Address.php +++ b/tests/Models/Address.php @@ -12,7 +12,6 @@ class Address extends Model { use DocumentModel; - protected $primaryKey = '_id'; protected $keyType = 'string'; protected $connection = 'mongodb'; protected static $unguarded = true; diff --git a/tests/Models/Birthday.php b/tests/Models/Birthday.php index 65b703af1..27f9be2c0 100644 --- a/tests/Models/Birthday.php +++ b/tests/Models/Birthday.php @@ -16,7 +16,6 @@ class Birthday extends Model { use DocumentModel; - protected $primaryKey = '_id'; protected $keyType = 'string'; protected $connection = 'mongodb'; protected string $collection = 'birthday'; diff --git a/tests/Models/Client.php b/tests/Models/Client.php index 47fd91d03..243f9692a 100644 --- a/tests/Models/Client.php +++ b/tests/Models/Client.php @@ -14,7 +14,6 @@ class Client extends Model { use DocumentModel; - protected $primaryKey = '_id'; protected $keyType = 'string'; protected $connection = 'mongodb'; protected string $collection = 'clients'; diff --git a/tests/Models/Experience.php b/tests/Models/Experience.php index 37a44e4d1..5141ce132 100644 --- a/tests/Models/Experience.php +++ b/tests/Models/Experience.php @@ -12,7 +12,6 @@ class Experience extends Model { use DocumentModel; - protected $primaryKey = '_id'; protected $keyType = 'string'; protected $connection = 'mongodb'; protected string $collection = 'experiences'; diff --git a/tests/Models/Group.php b/tests/Models/Group.php index 689c6d599..d98252e39 100644 --- a/tests/Models/Group.php +++ b/tests/Models/Group.php @@ -12,7 +12,6 @@ class Group extends Model { use DocumentModel; - protected $primaryKey = '_id'; protected $keyType = 'string'; protected $connection = 'mongodb'; protected string $collection = 'groups'; @@ -20,6 +19,6 @@ class Group extends Model public function users(): BelongsToMany { - return $this->belongsToMany(User::class, 'users', 'groups', 'users', '_id', '_id', 'users'); + return $this->belongsToMany(User::class, 'users', 'groups', 'users', 'id', 'id', 'users'); } } diff --git a/tests/Models/Guarded.php b/tests/Models/Guarded.php index 9837e9222..ad04adc04 100644 --- a/tests/Models/Guarded.php +++ b/tests/Models/Guarded.php @@ -11,7 +11,6 @@ class Guarded extends Model { use DocumentModel; - protected $primaryKey = '_id'; protected $keyType = 'string'; protected $connection = 'mongodb'; protected string $collection = 'guarded'; diff --git a/tests/Models/HiddenAnimal.php b/tests/Models/HiddenAnimal.php index a47184fe7..240238da0 100644 --- a/tests/Models/HiddenAnimal.php +++ b/tests/Models/HiddenAnimal.php @@ -22,7 +22,6 @@ final class HiddenAnimal extends Model { use DocumentModel; - protected $primaryKey = '_id'; protected $keyType = 'string'; protected $fillable = [ 'name', diff --git a/tests/Models/IdIsBinaryUuid.php b/tests/Models/IdIsBinaryUuid.php index 2314b4b19..33cc86da3 100644 --- a/tests/Models/IdIsBinaryUuid.php +++ b/tests/Models/IdIsBinaryUuid.php @@ -12,11 +12,10 @@ class IdIsBinaryUuid extends Model { use DocumentModel; - protected $primaryKey = '_id'; protected $keyType = 'string'; protected $connection = 'mongodb'; protected static $unguarded = true; protected $casts = [ - '_id' => BinaryUuid::class, + 'id' => BinaryUuid::class, ]; } diff --git a/tests/Models/IdIsInt.php b/tests/Models/IdIsInt.php index 1f8d1ba88..bf7c9f47f 100644 --- a/tests/Models/IdIsInt.php +++ b/tests/Models/IdIsInt.php @@ -11,9 +11,8 @@ class IdIsInt extends Model { use DocumentModel; - protected $primaryKey = '_id'; protected $keyType = 'int'; protected $connection = 'mongodb'; protected static $unguarded = true; - protected $casts = ['_id' => 'int']; + protected $casts = ['id' => 'int']; } diff --git a/tests/Models/IdIsString.php b/tests/Models/IdIsString.php index 37ba1c424..fef6c36bf 100644 --- a/tests/Models/IdIsString.php +++ b/tests/Models/IdIsString.php @@ -11,9 +11,8 @@ class IdIsString extends Model { use DocumentModel; - protected $primaryKey = '_id'; protected $keyType = 'string'; protected $connection = 'mongodb'; protected static $unguarded = true; - protected $casts = ['_id' => 'string']; + protected $casts = ['id' => 'string']; } diff --git a/tests/Models/Item.php b/tests/Models/Item.php index bc0b29b7b..2b97f4be0 100644 --- a/tests/Models/Item.php +++ b/tests/Models/Item.php @@ -15,7 +15,6 @@ class Item extends Model { use DocumentModel; - protected $primaryKey = '_id'; protected $keyType = 'string'; protected $connection = 'mongodb'; protected string $collection = 'items'; diff --git a/tests/Models/Label.php b/tests/Models/Label.php index b392184d7..2fae69286 100644 --- a/tests/Models/Label.php +++ b/tests/Models/Label.php @@ -17,7 +17,6 @@ class Label extends Model { use DocumentModel; - protected $primaryKey = '_id'; protected $keyType = 'string'; protected $connection = 'mongodb'; protected string $collection = 'labels'; diff --git a/tests/Models/Location.php b/tests/Models/Location.php index 9621d388f..db87c0021 100644 --- a/tests/Models/Location.php +++ b/tests/Models/Location.php @@ -11,7 +11,6 @@ class Location extends Model { use DocumentModel; - protected $primaryKey = '_id'; protected $keyType = 'string'; protected $connection = 'mongodb'; protected string $collection = 'locations'; diff --git a/tests/Models/Photo.php b/tests/Models/Photo.php index ea3321337..5ab162f39 100644 --- a/tests/Models/Photo.php +++ b/tests/Models/Photo.php @@ -12,7 +12,6 @@ class Photo extends Model { use DocumentModel; - protected $primaryKey = '_id'; protected $keyType = 'string'; protected $connection = 'mongodb'; protected string $collection = 'photos'; diff --git a/tests/Models/Role.php b/tests/Models/Role.php index 7d0dce7b1..dc1eeb4cc 100644 --- a/tests/Models/Role.php +++ b/tests/Models/Role.php @@ -12,7 +12,6 @@ class Role extends Model { use DocumentModel; - protected $primaryKey = '_id'; protected $keyType = 'string'; protected $connection = 'mongodb'; protected string $collection = 'roles'; diff --git a/tests/Models/Scoped.php b/tests/Models/Scoped.php index 84b8b81f7..7d26b3644 100644 --- a/tests/Models/Scoped.php +++ b/tests/Models/Scoped.php @@ -12,7 +12,6 @@ class Scoped extends Model { use DocumentModel; - protected $primaryKey = '_id'; protected $keyType = 'string'; protected $connection = 'mongodb'; protected string $collection = 'scoped'; diff --git a/tests/Models/Skill.php b/tests/Models/Skill.php index 90c9455b9..ad19458b0 100644 --- a/tests/Models/Skill.php +++ b/tests/Models/Skill.php @@ -12,7 +12,6 @@ class Skill extends Model { use DocumentModel; - protected $primaryKey = '_id'; protected $keyType = 'string'; protected $connection = 'mongodb'; protected string $collection = 'skills'; diff --git a/tests/Models/Soft.php b/tests/Models/Soft.php index 549e63758..172b83ea7 100644 --- a/tests/Models/Soft.php +++ b/tests/Models/Soft.php @@ -18,7 +18,6 @@ class Soft extends Model use SoftDeletes; use MassPrunable; - protected $primaryKey = '_id'; protected $keyType = 'string'; protected $connection = 'mongodb'; protected string $collection = 'soft'; diff --git a/tests/Models/User.php b/tests/Models/User.php index 22048f282..4033fe0f6 100644 --- a/tests/Models/User.php +++ b/tests/Models/User.php @@ -38,7 +38,6 @@ class User extends Model implements AuthenticatableContract, CanResetPasswordCon use Notifiable; use MassPrunable; - protected $primaryKey = '_id'; protected $keyType = 'string'; protected $connection = 'mongodb'; protected $casts = [ @@ -100,7 +99,7 @@ public function clients() public function groups() { - return $this->belongsToMany(Group::class, 'groups', 'users', 'groups', '_id', '_id', 'groups'); + return $this->belongsToMany(Group::class, 'groups', 'users', 'groups', 'id', 'id', 'groups'); } public function photos() diff --git a/tests/Query/AggregationBuilderTest.php b/tests/Query/AggregationBuilderTest.php index b3828597d..adbf21ff8 100644 --- a/tests/Query/AggregationBuilderTest.php +++ b/tests/Query/AggregationBuilderTest.php @@ -73,10 +73,10 @@ public function testCreateAggregationBuilder(): void $results = $pipeline->get(); $this->assertInstanceOf(Collection::class, $results); $this->assertCount(1, $results); - $this->assertInstanceOf(ObjectId::class, $results->first()['_id']); - $this->assertSame('John Doe', $results->first()['name']); - $this->assertIsInt($results->first()['year']); - $this->assertArrayNotHasKey('birthday', $results->first()); + $this->assertInstanceOf(ObjectId::class, $results->first()->_id); + $this->assertSame('John Doe', $results->first()->name); + $this->assertIsInt($results->first()->year); + $this->assertObjectNotHasProperty('birthday', $results->first()); // Execute the pipeline and validate the results in a lazy collection $results = $pipeline->cursor(); @@ -84,9 +84,9 @@ public function testCreateAggregationBuilder(): void // Execute the pipeline and return the first result $result = $pipeline->first(); - $this->assertIsArray($result); - $this->assertInstanceOf(ObjectId::class, $result['_id']); - $this->assertSame('John Doe', $result['name']); + $this->assertInstanceOf(\stdClass::class, $result); + $this->assertInstanceOf(ObjectId::class, $result->_id); + $this->assertSame('John Doe', $result->name); } public function testAddRawStage(): void diff --git a/tests/Query/BuilderTest.php b/tests/Query/BuilderTest.php index 05263981e..feeecc75b 100644 --- a/tests/Query/BuilderTest.php +++ b/tests/Query/BuilderTest.php @@ -39,11 +39,11 @@ public function testMql(array $expected, Closure $build): void // Operations that return a Cursor expect a "typeMap" option. if (isset($expected['find'][1])) { - $expected['find'][1]['typeMap'] = ['root' => 'array', 'document' => 'array']; + $expected['find'][1]['typeMap'] = ['root' => 'object', 'document' => 'array']; } if (isset($expected['aggregate'][1])) { - $expected['aggregate'][1]['typeMap'] = ['root' => 'array', 'document' => 'array']; + $expected['aggregate'][1]['typeMap'] = ['root' => 'object', 'document' => 'array']; } // Compare with assertEquals because the query can contain BSON objects. @@ -125,10 +125,9 @@ public static function provideQueryBuilderToMql(): iterable // Nested array are not flattened like in the Eloquent builder. MongoDB can compare objects. // When id is used as data field name, it's not converted to _id - $array = [['issue' => 45582], ['id' => 2], [3]]; yield 'whereIn nested array' => [ - ['find' => [['_id' => ['$in' => $array]], []]], - fn (Builder $builder) => $builder->whereIn('id', $array), + ['find' => [['_id' => ['$in' => [['issue' => 45582], ['_id' => 2], [3]]]], []]], + fn (Builder $builder) => $builder->whereIn('id', [['issue' => 45582], ['id' => 2], [3]]), ]; yield 'orWhereIn' => [ @@ -1335,7 +1334,7 @@ public static function provideExceptions(): iterable yield 'orderBy invalid direction' => [ InvalidArgumentException::class, 'Order direction must be "asc" or "desc"', - fn (Builder $builder) => $builder->orderBy('_id', 'dasc'), + fn (Builder $builder) => $builder->orderBy('id', 'dasc'), ]; /** @see DatabaseQueryBuilderTest::testWhereBetweens */ diff --git a/tests/QueryBuilderTest.php b/tests/QueryBuilderTest.php index 0163bdeae..8cb5e3116 100644 --- a/tests/QueryBuilderTest.php +++ b/tests/QueryBuilderTest.php @@ -59,7 +59,7 @@ public function testDeleteWithId() $product = DB::collection('items')->first(); - $pid = (string) ($product['_id']); + $pid = (string) ($product->id); DB::collection('items')->where('user_id', $userId)->delete($pid); @@ -67,7 +67,7 @@ public function testDeleteWithId() $product = DB::collection('items')->first(); - $pid = $product['_id']; + $pid = $product->id; DB::collection('items')->where('user_id', $userId)->delete($pid); @@ -100,7 +100,7 @@ public function testNoDocument() $item = DB::collection('items')->where('name', 'nothing')->first(); $this->assertNull($item); - $item = DB::collection('items')->where('_id', '51c33d8981fec6813e00000a')->first(); + $item = DB::collection('items')->where('id', '51c33d8981fec6813e00000a')->first(); $this->assertNull($item); } @@ -115,8 +115,8 @@ public function testInsert() $this->assertCount(1, $users); $user = $users[0]; - $this->assertEquals('John Doe', $user['name']); - $this->assertIsArray($user['tags']); + $this->assertEquals('John Doe', $user->name); + $this->assertIsArray($user->tags); } public function testInsertGetId() @@ -140,7 +140,7 @@ public function testBatchInsert() $users = DB::collection('users')->get(); $this->assertCount(2, $users); - $this->assertIsArray($users[0]['tags']); + $this->assertIsArray($users[0]->tags); } public function testFind() @@ -148,7 +148,7 @@ public function testFind() $id = DB::collection('users')->insertGetId(['name' => 'John Doe']); $user = DB::collection('users')->find($id); - $this->assertEquals('John Doe', $user['name']); + $this->assertEquals('John Doe', $user->name); } public function testFindWithTimeout() @@ -210,8 +210,8 @@ public function testUpdate() $john = DB::collection('users')->where('name', 'John Doe')->first(); $jane = DB::collection('users')->where('name', 'Jane Doe')->first(); - $this->assertEquals(100, $john['age']); - $this->assertEquals(20, $jane['age']); + $this->assertEquals(100, $john->age); + $this->assertEquals(20, $jane->age); } public function testUpdateOperators() @@ -238,12 +238,12 @@ public function testUpdateOperators() $john = DB::collection('users')->where('name', 'John Doe')->first(); $jane = DB::collection('users')->where('name', 'Jane Doe')->first(); - $this->assertArrayNotHasKey('age', $john); - $this->assertTrue($john['ageless']); + $this->assertObjectNotHasProperty('age', $john); + $this->assertTrue($john->ageless); - $this->assertEquals(21, $jane['age']); - $this->assertEquals('she', $jane['pronoun']); - $this->assertFalse($jane['ageless']); + $this->assertEquals(21, $jane->age); + $this->assertEquals('she', $jane->pronoun); + $this->assertFalse($jane->ageless); } public function testDelete() @@ -285,7 +285,7 @@ public function testSubKey() $users = DB::collection('users')->where('address.country', 'Belgium')->get(); $this->assertCount(1, $users); - $this->assertEquals('John Doe', $users[0]['name']); + $this->assertEquals('John Doe', $users[0]->name); } public function testInArray() @@ -328,7 +328,7 @@ public function testRaw() $results = DB::collection('users')->whereRaw(['age' => 20])->get(); $this->assertCount(1, $results); - $this->assertEquals('Jane Doe', $results[0]['name']); + $this->assertEquals('Jane Doe', $results[0]->name); } public function testPush() @@ -339,52 +339,52 @@ public function testPush() 'messages' => [], ]); - DB::collection('users')->where('_id', $id)->push('tags', 'tag1'); + DB::collection('users')->where('id', $id)->push('tags', 'tag1'); $user = DB::collection('users')->find($id); - $this->assertIsArray($user['tags']); - $this->assertCount(1, $user['tags']); - $this->assertEquals('tag1', $user['tags'][0]); + $this->assertIsArray($user->tags); + $this->assertCount(1, $user->tags); + $this->assertEquals('tag1', $user->tags[0]); - DB::collection('users')->where('_id', $id)->push('tags', 'tag2'); + DB::collection('users')->where('id', $id)->push('tags', 'tag2'); $user = DB::collection('users')->find($id); - $this->assertCount(2, $user['tags']); - $this->assertEquals('tag2', $user['tags'][1]); + $this->assertCount(2, $user->tags); + $this->assertEquals('tag2', $user->tags[1]); // Add duplicate - DB::collection('users')->where('_id', $id)->push('tags', 'tag2'); + DB::collection('users')->where('id', $id)->push('tags', 'tag2'); $user = DB::collection('users')->find($id); - $this->assertCount(3, $user['tags']); + $this->assertCount(3, $user->tags); // Add unique - DB::collection('users')->where('_id', $id)->push('tags', 'tag1', true); + DB::collection('users')->where('id', $id)->push('tags', 'tag1', true); $user = DB::collection('users')->find($id); - $this->assertCount(3, $user['tags']); + $this->assertCount(3, $user->tags); $message = ['from' => 'Jane', 'body' => 'Hi John']; - DB::collection('users')->where('_id', $id)->push('messages', $message); + DB::collection('users')->where('id', $id)->push('messages', $message); $user = DB::collection('users')->find($id); - $this->assertIsArray($user['messages']); - $this->assertCount(1, $user['messages']); - $this->assertEquals($message, $user['messages'][0]); + $this->assertIsArray($user->messages); + $this->assertCount(1, $user->messages); + $this->assertEquals($message, $user->messages[0]); // Raw - DB::collection('users')->where('_id', $id)->push([ + DB::collection('users')->where('id', $id)->push([ 'tags' => 'tag3', 'messages' => ['from' => 'Mark', 'body' => 'Hi John'], ]); $user = DB::collection('users')->find($id); - $this->assertCount(4, $user['tags']); - $this->assertCount(2, $user['messages']); + $this->assertCount(4, $user->tags); + $this->assertCount(2, $user->messages); - DB::collection('users')->where('_id', $id)->push([ + DB::collection('users')->where('id', $id)->push([ 'messages' => [ 'date' => new DateTime(), 'body' => 'Hi John', ], ]); $user = DB::collection('users')->find($id); - $this->assertCount(3, $user['messages']); + $this->assertCount(3, $user->messages); } public function testPushRefuses2ndArgumentWhen1stIsAnArray() @@ -406,24 +406,24 @@ public function testPull() 'messages' => [$message1, $message2], ]); - DB::collection('users')->where('_id', $id)->pull('tags', 'tag3'); + DB::collection('users')->where('id', $id)->pull('tags', 'tag3'); $user = DB::collection('users')->find($id); - $this->assertIsArray($user['tags']); - $this->assertCount(3, $user['tags']); - $this->assertEquals('tag4', $user['tags'][2]); + $this->assertIsArray($user->tags); + $this->assertCount(3, $user->tags); + $this->assertEquals('tag4', $user->tags[2]); - DB::collection('users')->where('_id', $id)->pull('messages', $message1); + DB::collection('users')->where('id', $id)->pull('messages', $message1); $user = DB::collection('users')->find($id); - $this->assertIsArray($user['messages']); - $this->assertCount(1, $user['messages']); + $this->assertIsArray($user->messages); + $this->assertCount(1, $user->messages); // Raw - DB::collection('users')->where('_id', $id)->pull(['tags' => 'tag2', 'messages' => $message2]); + DB::collection('users')->where('id', $id)->pull(['tags' => 'tag2', 'messages' => $message2]); $user = DB::collection('users')->find($id); - $this->assertCount(2, $user['tags']); - $this->assertCount(0, $user['messages']); + $this->assertCount(2, $user->tags); + $this->assertCount(0, $user->messages); } public function testDistinct() @@ -449,24 +449,24 @@ public function testDistinct() public function testCustomId() { DB::collection('items')->insert([ - ['_id' => 'knife', 'type' => 'sharp', 'amount' => 34], - ['_id' => 'fork', 'type' => 'sharp', 'amount' => 20], - ['_id' => 'spoon', 'type' => 'round', 'amount' => 3], + ['id' => 'knife', 'type' => 'sharp', 'amount' => 34], + ['id' => 'fork', 'type' => 'sharp', 'amount' => 20], + ['id' => 'spoon', 'type' => 'round', 'amount' => 3], ]); $item = DB::collection('items')->find('knife'); - $this->assertEquals('knife', $item['_id']); + $this->assertEquals('knife', $item->id); - $item = DB::collection('items')->where('_id', 'fork')->first(); - $this->assertEquals('fork', $item['_id']); + $item = DB::collection('items')->where('id', 'fork')->first(); + $this->assertEquals('fork', $item->id); DB::collection('users')->insert([ - ['_id' => 1, 'name' => 'Jane Doe'], - ['_id' => 2, 'name' => 'John Doe'], + ['id' => 1, 'name' => 'Jane Doe'], + ['id' => 2, 'name' => 'John Doe'], ]); $item = DB::collection('users')->find(1); - $this->assertEquals(1, $item['_id']); + $this->assertEquals(1, $item->id); } public function testTake() @@ -480,7 +480,7 @@ public function testTake() $items = DB::collection('items')->orderBy('name')->take(2)->get(); $this->assertCount(2, $items); - $this->assertEquals('fork', $items[0]['name']); + $this->assertEquals('fork', $items[0]->name); } public function testSkip() @@ -494,7 +494,7 @@ public function testSkip() $items = DB::collection('items')->orderBy('name')->skip(2)->get(); $this->assertCount(2, $items); - $this->assertEquals('spoon', $items[0]['name']); + $this->assertEquals('spoon', $items[0]->name); } public function testPluck() @@ -526,7 +526,7 @@ public function testList() $this->assertCount(3, $list); $this->assertEquals(['knife' => 'sharp', 'fork' => 'sharp', 'spoon' => 'round'], $list); - $list = DB::collection('items')->pluck('name', '_id')->toArray(); + $list = DB::collection('items')->pluck('name', 'id')->toArray(); $this->assertCount(4, $list); $this->assertEquals(24, strlen(key($list))); } @@ -618,52 +618,52 @@ public function testUnset() $user1 = DB::collection('users')->find($id1); $user2 = DB::collection('users')->find($id2); - $this->assertArrayNotHasKey('note1', $user1); - $this->assertArrayHasKey('note2', $user1); - $this->assertArrayHasKey('note1', $user2); - $this->assertArrayHasKey('note2', $user2); + $this->assertObjectNotHasProperty('note1', $user1); + $this->assertObjectHasProperty('note2', $user1); + $this->assertObjectHasProperty('note1', $user2); + $this->assertObjectHasProperty('note2', $user2); DB::collection('users')->where('name', 'Jane Doe')->unset(['note1', 'note2']); $user2 = DB::collection('users')->find($id2); - $this->assertArrayNotHasKey('note1', $user2); - $this->assertArrayNotHasKey('note2', $user2); + $this->assertObjectNotHasProperty('note1', $user2); + $this->assertObjectNotHasProperty('note2', $user2); } public function testUpdateSubdocument() { $id = DB::collection('users')->insertGetId(['name' => 'John Doe', 'address' => ['country' => 'Belgium']]); - DB::collection('users')->where('_id', $id)->update(['address.country' => 'England']); + DB::collection('users')->where('id', $id)->update(['address.country' => 'England']); $check = DB::collection('users')->find($id); - $this->assertEquals('England', $check['address']['country']); + $this->assertEquals('England', $check->address['country']); } public function testDates() { DB::collection('users')->insert([ - ['name' => 'John Doe', 'birthday' => new UTCDateTime(Date::parse('1980-01-01 00:00:00'))], - ['name' => 'Robert Roe', 'birthday' => new UTCDateTime(Date::parse('1982-01-01 00:00:00'))], - ['name' => 'Mark Moe', 'birthday' => new UTCDateTime(Date::parse('1983-01-01 00:00:00.1'))], - ['name' => 'Frank White', 'birthday' => new UTCDateTime(Date::parse('1960-01-01 12:12:12.1'))], + ['name' => 'John Doe', 'birthday' => Date::parse('1980-01-01 00:00:00')], + ['name' => 'Robert Roe', 'birthday' => new DateTimeImmutable('1982-01-01 00:00:00')], + ['name' => 'Mark Moe', 'birthday' => new DateTime('1983-01-01 00:00:00.1')], + ['name' => 'Frank White', 'birthday' => Date::parse('1960-01-01 12:12:12.1')], ]); $user = DB::collection('users') - ->where('birthday', new UTCDateTime(Date::parse('1980-01-01 00:00:00'))) + ->where('birthday', Date::parse('1980-01-01 00:00:00')) ->first(); - $this->assertEquals('John Doe', $user['name']); + $this->assertEquals('John Doe', $user->name); $user = DB::collection('users') - ->where('birthday', new UTCDateTime(Date::parse('1960-01-01 12:12:12.1'))) + ->where('birthday', Date::parse('1960-01-01 12:12:12.1')) ->first(); - $this->assertEquals('Frank White', $user['name']); + $this->assertEquals('Frank White', $user->name); $user = DB::collection('users')->where('birthday', '=', new DateTime('1980-01-01 00:00:00'))->first(); - $this->assertEquals('John Doe', $user['name']); + $this->assertEquals('John Doe', $user->name); - $start = new UTCDateTime(1000 * strtotime('1950-01-01 00:00:00')); - $stop = new UTCDateTime(1000 * strtotime('1981-01-01 00:00:00')); + $start = Date::parse('1950-01-01 00:00:00'); + $stop = Date::parse('1981-01-01 00:00:00'); $users = DB::collection('users')->whereBetween('birthday', [$start, $stop])->get(); $this->assertCount(2, $users); @@ -706,25 +706,25 @@ public function testOperators() $results = DB::collection('users')->where('age', 'exists', true)->get(); $this->assertCount(2, $results); - $resultsNames = [$results[0]['name'], $results[1]['name']]; + $resultsNames = [$results[0]->name, $results[1]->name]; $this->assertContains('John Doe', $resultsNames); $this->assertContains('Robert Roe', $resultsNames); $results = DB::collection('users')->where('age', 'exists', false)->get(); $this->assertCount(1, $results); - $this->assertEquals('Jane Doe', $results[0]['name']); + $this->assertEquals('Jane Doe', $results[0]->name); $results = DB::collection('users')->where('age', 'type', 2)->get(); $this->assertCount(1, $results); - $this->assertEquals('Robert Roe', $results[0]['name']); + $this->assertEquals('Robert Roe', $results[0]->name); $results = DB::collection('users')->where('age', 'mod', [15, 0])->get(); $this->assertCount(1, $results); - $this->assertEquals('John Doe', $results[0]['name']); + $this->assertEquals('John Doe', $results[0]->name); $results = DB::collection('users')->where('age', 'mod', [29, 1])->get(); $this->assertCount(1, $results); - $this->assertEquals('John Doe', $results[0]['name']); + $this->assertEquals('John Doe', $results[0]->name); $results = DB::collection('users')->where('age', 'mod', [14, 0])->get(); $this->assertCount(0, $results); @@ -789,7 +789,7 @@ public function testOperators() $users = DB::collection('users')->where('addresses', 'elemMatch', ['city' => 'Brussels'])->get(); $this->assertCount(1, $users); - $this->assertEquals('Jane Doe', $users[0]['name']); + $this->assertEquals('Jane Doe', $users[0]->name); } public function testIncrement() @@ -802,43 +802,43 @@ public function testIncrement() ]); $user = DB::collection('users')->where('name', 'John Doe')->first(); - $this->assertEquals(30, $user['age']); + $this->assertEquals(30, $user->age); DB::collection('users')->where('name', 'John Doe')->increment('age'); $user = DB::collection('users')->where('name', 'John Doe')->first(); - $this->assertEquals(31, $user['age']); + $this->assertEquals(31, $user->age); DB::collection('users')->where('name', 'John Doe')->decrement('age'); $user = DB::collection('users')->where('name', 'John Doe')->first(); - $this->assertEquals(30, $user['age']); + $this->assertEquals(30, $user->age); DB::collection('users')->where('name', 'John Doe')->increment('age', 5); $user = DB::collection('users')->where('name', 'John Doe')->first(); - $this->assertEquals(35, $user['age']); + $this->assertEquals(35, $user->age); DB::collection('users')->where('name', 'John Doe')->decrement('age', 5); $user = DB::collection('users')->where('name', 'John Doe')->first(); - $this->assertEquals(30, $user['age']); + $this->assertEquals(30, $user->age); DB::collection('users')->where('name', 'Jane Doe')->increment('age', 10, ['note' => 'adult']); $user = DB::collection('users')->where('name', 'Jane Doe')->first(); - $this->assertEquals(20, $user['age']); - $this->assertEquals('adult', $user['note']); + $this->assertEquals(20, $user->age); + $this->assertEquals('adult', $user->note); DB::collection('users')->where('name', 'John Doe')->decrement('age', 20, ['note' => 'minor']); $user = DB::collection('users')->where('name', 'John Doe')->first(); - $this->assertEquals(10, $user['age']); - $this->assertEquals('minor', $user['note']); + $this->assertEquals(10, $user->age); + $this->assertEquals('minor', $user->note); DB::collection('users')->increment('age'); $user = DB::collection('users')->where('name', 'John Doe')->first(); - $this->assertEquals(11, $user['age']); + $this->assertEquals(11, $user->age); $user = DB::collection('users')->where('name', 'Jane Doe')->first(); - $this->assertEquals(21, $user['age']); + $this->assertEquals(21, $user->age); $user = DB::collection('users')->where('name', 'Robert Roe')->first(); - $this->assertNull($user['age']); + $this->assertNull($user->age); $user = DB::collection('users')->where('name', 'Mark Moe')->first(); - $this->assertEquals(1, $user['age']); + $this->assertEquals(1, $user->age); } public function testProjections() @@ -852,7 +852,7 @@ public function testProjections() $results = DB::collection('items')->project(['tags' => ['$slice' => 1]])->get(); foreach ($results as $result) { - $this->assertEquals(1, count($result['tags'])); + $this->assertEquals(1, count($result->tags)); } } @@ -879,15 +879,15 @@ public function testHintOptions() $results = DB::collection('items')->hint(['$natural' => -1])->get(); - $this->assertEquals('spoon', $results[0]['name']); - $this->assertEquals('spork', $results[1]['name']); - $this->assertEquals('fork', $results[2]['name']); + $this->assertEquals('spoon', $results[0]->name); + $this->assertEquals('spork', $results[1]->name); + $this->assertEquals('fork', $results[2]->name); $results = DB::collection('items')->hint(['$natural' => 1])->get(); - $this->assertEquals('spoon', $results[2]['name']); - $this->assertEquals('spork', $results[1]['name']); - $this->assertEquals('fork', $results[0]['name']); + $this->assertEquals('spoon', $results[2]->name); + $this->assertEquals('spork', $results[1]->name); + $this->assertEquals('fork', $results[0]->name); } public function testCursor() @@ -899,11 +899,11 @@ public function testCursor() ]; DB::collection('items')->insert($data); - $results = DB::collection('items')->orderBy('_id', 'asc')->cursor(); + $results = DB::collection('items')->orderBy('id', 'asc')->cursor(); $this->assertInstanceOf(LazyCollection::class, $results); foreach ($results as $i => $result) { - $this->assertEquals($data[$i]['name'], $result['name']); + $this->assertEquals($data[$i]['name'], $result->name); } } @@ -918,52 +918,52 @@ public function testStringableColumn() $this->assertInstanceOf(Stringable::class, $nameColumn, 'Ensure we are testing the feature with a Stringable instance'); $user = DB::collection('users')->where($nameColumn, 'John Doe')->first(); - $this->assertEquals('John Doe', $user['name']); + $this->assertEquals('John Doe', $user->name); // Test this other document to be sure this is not a random success to data order $user = DB::collection('users')->where($nameColumn, 'Jane Doe')->orderBy('natural')->first(); - $this->assertEquals('Jane Doe', $user['name']); + $this->assertEquals('Jane Doe', $user->name); // With an operator $user = DB::collection('users')->where($nameColumn, '!=', 'Jane Doe')->first(); - $this->assertEquals('John Doe', $user['name']); + $this->assertEquals('John Doe', $user->name); // whereIn and whereNotIn $user = DB::collection('users')->whereIn($nameColumn, ['John Doe'])->first(); - $this->assertEquals('John Doe', $user['name']); + $this->assertEquals('John Doe', $user->name); $user = DB::collection('users')->whereNotIn($nameColumn, ['John Doe'])->first(); - $this->assertEquals('Jane Doe', $user['name']); + $this->assertEquals('Jane Doe', $user->name); $ageColumn = Str::of('age'); // whereBetween and whereNotBetween $user = DB::collection('users')->whereBetween($ageColumn, [30, 40])->first(); - $this->assertEquals('Jane Doe', $user['name']); + $this->assertEquals('Jane Doe', $user->name); // whereBetween and whereNotBetween $user = DB::collection('users')->whereNotBetween($ageColumn, [30, 40])->first(); - $this->assertEquals('John Doe', $user['name']); + $this->assertEquals('John Doe', $user->name); $birthdayColumn = Str::of('birthday'); // whereDate $user = DB::collection('users')->whereDate($birthdayColumn, '1995-01-01')->first(); - $this->assertEquals('John Doe', $user['name']); + $this->assertEquals('John Doe', $user->name); $user = DB::collection('users')->whereDate($birthdayColumn, '<', '1990-01-01') ->orderBy($birthdayColumn, 'desc')->first(); - $this->assertEquals('Jane Doe', $user['name']); + $this->assertEquals('Jane Doe', $user->name); $user = DB::collection('users')->whereDate($birthdayColumn, '>', '1990-01-01') ->orderBy($birthdayColumn, 'asc')->first(); - $this->assertEquals('John Doe', $user['name']); + $this->assertEquals('John Doe', $user->name); $user = DB::collection('users')->whereDate($birthdayColumn, '!=', '1987-01-01')->first(); - $this->assertEquals('John Doe', $user['name']); + $this->assertEquals('John Doe', $user->name); // increment DB::collection('users')->where($ageColumn, 28)->increment($ageColumn, 1); $user = DB::collection('users')->where($ageColumn, 29)->first(); - $this->assertEquals('John Doe', $user['name']); + $this->assertEquals('John Doe', $user->name); } #[TestWith(['id', 'id'])] @@ -974,11 +974,11 @@ public function testIdAlias($insertId, $queryId): void DB::collection('items')->insert([$insertId => 'abc', 'name' => 'Karting']); $item = DB::collection('items')->where($queryId, '=', 'abc')->first(); $this->assertNotNull($item); - $this->assertSame('abc', $item['_id']); - $this->assertSame('Karting', $item['name']); + $this->assertSame('abc', $item->id); + $this->assertSame('Karting', $item->name); DB::collection('items')->where($insertId, '=', 'abc')->update(['name' => 'Bike']); $item = DB::collection('items')->where($queryId, '=', 'abc')->first(); - $this->assertSame('Bike', $item['name']); + $this->assertSame('Bike', $item->name); } } diff --git a/tests/QueryTest.php b/tests/QueryTest.php index 2fd66bf70..e228a0f70 100644 --- a/tests/QueryTest.php +++ b/tests/QueryTest.php @@ -405,7 +405,7 @@ public function testCount(): void $this->assertEquals(6, $count); // Test for issue #165 - $count = User::select('_id', 'age', 'title')->where('age', '<>', 35)->count(); + $count = User::select('id', 'age', 'title')->where('age', '<>', 35)->count(); $this->assertEquals(6, $count); } diff --git a/tests/Queue/Failed/MongoFailedJobProviderTest.php b/tests/Queue/Failed/MongoFailedJobProviderTest.php index f113428ec..7996b5723 100644 --- a/tests/Queue/Failed/MongoFailedJobProviderTest.php +++ b/tests/Queue/Failed/MongoFailedJobProviderTest.php @@ -57,8 +57,7 @@ public function testLog(): void $this->assertSame('default', $inserted->queue); $this->assertSame('{"foo":"bar"}', $inserted->payload); $this->assertStringContainsString('OutOfBoundsException: This is the error', $inserted->exception); - $this->assertInstanceOf(ObjectId::class, $inserted->_id); - $this->assertSame((string) $inserted->_id, $inserted->id); + $this->assertInstanceOf(ObjectId::class, $inserted->id); } public function testCount(): void @@ -75,7 +74,7 @@ public function testAll(): void $all = $this->getProvider()->all(); $this->assertCount(5, $all); - $this->assertEquals(new ObjectId(sprintf('%024d', 5)), $all[0]->_id); + $this->assertEquals(new ObjectId(sprintf('%024d', 5)), $all[0]->id); $this->assertEquals(sprintf('%024d', 5), $all[0]->id, 'id field is added for compatibility with DatabaseFailedJobProvider'); } @@ -87,7 +86,7 @@ public function testFindAndForget(): void $found = $provider->find($id); $this->assertIsObject($found, 'The job is found'); - $this->assertEquals(new ObjectId($id), $found->_id); + $this->assertEquals(new ObjectId($id), $found->id); $this->assertObjectHasProperty('failed_at', $found); // Delete the job @@ -117,7 +116,7 @@ public function testIdsFilteredByQuery(): void $ids = $this->getProvider()->ids('other'); $this->assertCount(2, $ids); - $this->assertEquals(new ObjectId(sprintf('%024d', 4)), $ids[0]); + $this->assertEquals(sprintf('%024d', 4), $ids[0]); } public function testFlush(): void diff --git a/tests/QueueTest.php b/tests/QueueTest.php index 2236fba1b..ce6458dad 100644 --- a/tests/QueueTest.php +++ b/tests/QueueTest.php @@ -71,7 +71,7 @@ public function testQueueJobExpired(): void $expiry = Carbon::now()->subSeconds(Config::get('queue.connections.database.expire'))->getTimestamp(); Queue::getDatabase() ->table(Config::get('queue.connections.database.table')) - ->where('_id', $id) + ->where('id', $id) ->update(['reserved' => 1, 'reserved_at' => $expiry]); // Expect an attempted older job in the queue @@ -83,13 +83,6 @@ public function testQueueJobExpired(): void $this->assertEquals(0, Queue::getDatabase()->table(Config::get('queue.connections.database.table'))->count()); } - public function testFailQueueJob(): void - { - $provider = app('queue.failer'); - - $this->assertInstanceOf(MongoFailedJobProvider::class, $provider); - } - public function testFindFailJobNull(): void { Config::set('queue.failed.database', 'mongodb'); @@ -114,7 +107,7 @@ public function testIncrementAttempts(): void ->get(); $this->assertCount(1, $othersJobs); - $this->assertEquals(0, $othersJobs[0]['attempts']); + $this->assertEquals(0, $othersJobs[0]->attempts); } public function testJobRelease(): void @@ -131,7 +124,7 @@ public function testJobRelease(): void ->get(); $this->assertCount(1, $jobs); - $this->assertEquals(1, $jobs[0]['attempts']); + $this->assertEquals(1, $jobs[0]->attempts); } public function testQueueDeleteReserved(): void @@ -158,18 +151,18 @@ public function testQueueRelease(): void $releasedJob = Queue::getDatabase() ->table(Config::get('queue.connections.database.table')) - ->where('_id', $releasedJobId) + ->where('id', $releasedJobId) ->first(); - $this->assertEquals($queue, $releasedJob['queue']); - $this->assertEquals(1, $releasedJob['attempts']); - $this->assertNull($releasedJob['reserved_at']); + $this->assertEquals($queue, $releasedJob->queue); + $this->assertEquals(1, $releasedJob->attempts); + $this->assertNull($releasedJob->reserved_at); $this->assertEquals( Carbon::now()->addRealSeconds($delay)->getTimestamp(), - $releasedJob['available_at'], + $releasedJob->available_at, ); - $this->assertEquals(Carbon::now()->getTimestamp(), $releasedJob['created_at']); - $this->assertEquals($job->getRawBody(), $releasedJob['payload']); + $this->assertEquals(Carbon::now()->getTimestamp(), $releasedJob->created_at); + $this->assertEquals($job->getRawBody(), $releasedJob->payload); } public function testQueueDeleteAndRelease(): void @@ -194,10 +187,10 @@ public function testFailedJobLogging() $failedJob = Queue::getDatabase()->table(Config::get('queue.failed.table'))->first(); - $this->assertSame('test_connection', $failedJob['connection']); - $this->assertSame('test_queue', $failedJob['queue']); - $this->assertSame('test_payload', $failedJob['payload']); - $this->assertEquals(new UTCDateTime(Carbon::now()), $failedJob['failed_at']); - $this->assertStringStartsWith('Exception: test_exception in ', $failedJob['exception']); + $this->assertSame('test_connection', $failedJob->connection); + $this->assertSame('test_queue', $failedJob->queue); + $this->assertSame('test_payload', $failedJob->payload); + $this->assertEquals(Carbon::now(), $failedJob->failed_at); + $this->assertStringStartsWith('Exception: test_exception in ', $failedJob->exception); } } diff --git a/tests/RelationsTest.php b/tests/RelationsTest.php index 02efbc77b..902f0499c 100644 --- a/tests/RelationsTest.php +++ b/tests/RelationsTest.php @@ -40,16 +40,16 @@ public function tearDown(): void public function testHasMany(): void { $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]); + 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->assertCount(2, $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' => '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; @@ -59,32 +59,32 @@ public function testHasMany(): void public function testHasManyWithTrashed(): void { $user = User::create(['name' => 'George R. R. Martin']); - $first = Soft::create(['title' => 'A Game of Thrones', 'user_id' => $user->_id]); - $second = Soft::create(['title' => 'The Witcher', 'user_id' => $user->_id]); + $first = Soft::create(['title' => 'A Game of Thrones', 'user_id' => $user->id]); + $second = Soft::create(['title' => 'The Witcher', 'user_id' => $user->id]); self::assertNull($first->deleted_at); - self::assertEquals($user->_id, $first->user->_id); - self::assertEquals([$first->_id, $second->_id], $user->softs->pluck('_id')->toArray()); + self::assertEquals($user->id, $first->user->id); + self::assertEquals([$first->id, $second->id], $user->softs->pluck('id')->toArray()); $first->delete(); $user->refresh(); self::assertNotNull($first->deleted_at); - self::assertEquals([$second->_id], $user->softs->pluck('_id')->toArray()); - self::assertEquals([$first->_id, $second->_id], $user->softsWithTrashed->pluck('_id')->toArray()); + self::assertEquals([$second->id], $user->softs->pluck('id')->toArray()); + self::assertEquals([$first->id, $second->id], $user->softsWithTrashed->pluck('id')->toArray()); } public function testBelongsTo(): void { $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]); + 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]); + $item = Item::create(['type' => 'sword', 'user_id' => $user->id]); $owner = $item->user; $this->assertEquals('John Doe', $owner->name); @@ -96,11 +96,11 @@ public function testBelongsTo(): void public function testHasOne(): void { $user = User::create(['name' => 'John Doe']); - Role::create(['type' => 'admin', 'user_id' => $user->_id]); + Role::create(['type' => 'admin', 'user_id' => $user->id]); $role = $user->role; $this->assertEquals('admin', $role->type); - $this->assertEquals($user->_id, $role->user_id); + $this->assertEquals($user->id, $role->user_id); $user = User::create(['name' => 'Jane Doe']); $role = new Role(['type' => 'user']); @@ -108,20 +108,20 @@ public function testHasOne(): void $role = $user->role; $this->assertEquals('user', $role->type); - $this->assertEquals($user->_id, $role->user_id); + $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); + $this->assertEquals($user->id, $role->user_id); } public function testWithBelongsTo(): void { $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' => '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(); @@ -136,12 +136,12 @@ public function testWithBelongsTo(): void public function testWithHashMany(): void { $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' => '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); + $user = User::with('items')->find($user->id); $items = $user->getRelation('items'); $this->assertCount(3, $items); @@ -151,10 +151,10 @@ public function testWithHashMany(): void public function testWithHasOne(): void { $user = User::create(['name' => 'John Doe']); - Role::create(['type' => 'admin', 'user_id' => $user->_id]); - Role::create(['type' => 'guest', 'user_id' => $user->_id]); + Role::create(['type' => 'admin', 'user_id' => $user->id]); + Role::create(['type' => 'guest', 'user_id' => $user->id]); - $user = User::with('role')->find($user->_id); + $user = User::with('role')->find($user->id); $role = $user->getRelation('role'); $this->assertInstanceOf(Role::class, $role); @@ -168,22 +168,22 @@ public function testEasyRelation(): void $item = Item::create(['type' => 'knife']); $user->items()->save($item); - $user = User::find($user->_id); + $user = User::find($user->id); $items = $user->items; $this->assertCount(1, $items); $this->assertInstanceOf(Item::class, $items[0]); - $this->assertEquals($user->_id, $items[0]->user_id); + $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); + $user = User::find($user->id); $role = $user->role; $this->assertInstanceOf(Role::class, $role); $this->assertEquals('admin', $role->type); - $this->assertEquals($user->_id, $role->user_id); + $this->assertEquals($user->id, $role->user_id); } public function testBelongsToMany(): void @@ -195,7 +195,7 @@ public function testBelongsToMany(): void $user->clients()->create(['name' => 'Buffet Bar Inc.']); // Refetch - $user = User::with('clients')->find($user->_id); + $user = User::with('clients')->find($user->id); $client = Client::with('users')->first(); // Check for relation attributes @@ -228,8 +228,8 @@ public function testBelongsToMany(): void $this->assertInstanceOf(User::class, $user); // Assert they are not attached - $this->assertNotContains($client->_id, $user->client_ids); - $this->assertNotContains($user->_id, $client->user_ids); + $this->assertNotContains($client->id, $user->client_ids); + $this->assertNotContains($user->id, $client->user_ids); $this->assertCount(1, $user->clients); $this->assertCount(1, $client->users); @@ -241,8 +241,8 @@ public function testBelongsToMany(): void $client = Client::Where('name', '=', 'Buffet Bar Inc.')->first(); // Assert they are attached - $this->assertContains($client->_id, $user->client_ids); - $this->assertContains($user->_id, $client->user_ids); + $this->assertContains($client->id, $user->client_ids); + $this->assertContains($user->id, $client->user_ids); $this->assertCount(2, $user->clients); $this->assertCount(2, $client->users); @@ -254,8 +254,8 @@ public function testBelongsToMany(): void $client = Client::Where('name', '=', 'Buffet Bar Inc.')->first(); // Assert they are not attached - $this->assertNotContains($client->_id, $user->client_ids); - $this->assertNotContains($user->_id, $client->user_ids); + $this->assertNotContains($client->id, $user->client_ids); + $this->assertNotContains($user->id, $client->user_ids); $this->assertCount(0, $user->clients); $this->assertCount(1, $client->users); } @@ -265,19 +265,19 @@ public function testBelongsToManyAttachesExistingModels(): void $user = User::create(['name' => 'John Doe', 'client_ids' => ['1234523']]); $clients = [ - Client::create(['name' => 'Pork Pies Ltd.'])->_id, - Client::create(['name' => 'Buffet Bar Inc.'])->_id, + 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, + 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); + $user = User::with('clients')->find($user->id); // Assert non attached ID's are detached successfully $this->assertNotContains('1234523', $user->client_ids); @@ -289,7 +289,7 @@ public function testBelongsToManyAttachesExistingModels(): void $user->clients()->sync($moreClients); // Refetch - $user = User::with('clients')->find($user->_id); + $user = User::with('clients')->find($user->id); // Assert there are now still 2 client objects in the relationship $this->assertCount(2, $user->clients); @@ -307,11 +307,11 @@ public function testBelongsToManySync(): void $client2 = Client::create(['name' => 'Buffet Bar Inc.']); // Sync multiple - $user->clients()->sync([$client1->_id, $client2->_id]); + $user->clients()->sync([$client1->id, $client2->id]); $this->assertCount(2, $user->clients); // Sync single wrapped by an array - $user->clients()->sync([$client1->_id]); + $user->clients()->sync([$client1->id]); $user->load('clients'); $this->assertCount(1, $user->clients); @@ -328,8 +328,8 @@ public function testBelongsToManySync(): void public function testBelongsToManyAttachArray(): void { $user = User::create(['name' => 'John Doe']); - $client1 = Client::create(['name' => 'Test 1'])->_id; - $client2 = Client::create(['name' => 'Test 2'])->_id; + $client1 = Client::create(['name' => 'Test 1'])->id; + $client2 = Client::create(['name' => 'Test 2'])->id; $user->clients()->attach([$client1, $client2]); $this->assertCount(2, $user->clients); @@ -353,27 +353,27 @@ public function testBelongsToManySyncWithCustomKeys(): void $skill1 = Skill::create(['cskill_id' => (string) (new ObjectId()), 'name' => 'PHP']); $skill2 = Skill::create(['cskill_id' => (string) (new ObjectId()), 'name' => 'Laravel']); - $client = Client::query()->find($client->_id); + $client = Client::query()->find($client->id); $client->skillsWithCustomKeys()->sync([$skill1->cskill_id, $skill2->cskill_id]); $this->assertCount(2, $client->skillsWithCustomKeys); self::assertIsString($skill1->cskill_id); self::assertContains($skill1->cskill_id, $client->skillsWithCustomKeys->pluck('cskill_id')); - self::assertNotContains($skill1->_id, $client->skillsWithCustomKeys->pluck('cskill_id')); + self::assertNotContains($skill1->id, $client->skillsWithCustomKeys->pluck('cskill_id')); self::assertIsString($skill2->cskill_id); self::assertContains($skill2->cskill_id, $client->skillsWithCustomKeys->pluck('cskill_id')); - self::assertNotContains($skill2->_id, $client->skillsWithCustomKeys->pluck('cskill_id')); + self::assertNotContains($skill2->id, $client->skillsWithCustomKeys->pluck('cskill_id')); - $check = Skill::query()->find($skill1->_id); + $check = Skill::query()->find($skill1->id); self::assertIsString($check->cskill_id); self::assertContains($check->cskill_id, $client->skillsWithCustomKeys->pluck('cskill_id')); - self::assertNotContains($check->_id, $client->skillsWithCustomKeys->pluck('cskill_id')); + self::assertNotContains($check->id, $client->skillsWithCustomKeys->pluck('cskill_id')); - $check = Skill::query()->find($skill2->_id); + $check = Skill::query()->find($skill2->id); self::assertIsString($check->cskill_id); self::assertContains($check->cskill_id, $client->skillsWithCustomKeys->pluck('cskill_id')); - self::assertNotContains($check->_id, $client->skillsWithCustomKeys->pluck('cskill_id')); + self::assertNotContains($check->id, $client->skillsWithCustomKeys->pluck('cskill_id')); } public function testBelongsToManySyncModelWithCustomKeys(): void @@ -381,18 +381,18 @@ public function testBelongsToManySyncModelWithCustomKeys(): void $client = Client::create(['cclient_id' => (string) (new ObjectId()), 'years' => '5']); $skill1 = Skill::create(['cskill_id' => (string) (new ObjectId()), 'name' => 'PHP']); - $client = Client::query()->find($client->_id); + $client = Client::query()->find($client->id); $client->skillsWithCustomKeys()->sync($skill1); $this->assertCount(1, $client->skillsWithCustomKeys); self::assertIsString($skill1->cskill_id); self::assertContains($skill1->cskill_id, $client->skillsWithCustomKeys->pluck('cskill_id')); - self::assertNotContains($skill1->_id, $client->skillsWithCustomKeys->pluck('cskill_id')); + self::assertNotContains($skill1->id, $client->skillsWithCustomKeys->pluck('cskill_id')); - $check = Skill::query()->find($skill1->_id); - self::assertIsString($check->_id); + $check = Skill::query()->find($skill1->id); + self::assertIsString($check->id); self::assertContains($check->cskill_id, $client->skillsWithCustomKeys->pluck('cskill_id')); - self::assertNotContains($check->_id, $client->skillsWithCustomKeys->pluck('cskill_id')); + self::assertNotContains($check->id, $client->skillsWithCustomKeys->pluck('cskill_id')); } public function testBelongsToManySyncEloquentCollectionWithCustomKeys(): void @@ -402,27 +402,27 @@ public function testBelongsToManySyncEloquentCollectionWithCustomKeys(): void $skill2 = Skill::create(['cskill_id' => (string) (new ObjectId()), 'name' => 'Laravel']); $collection = new Collection([$skill1, $skill2]); - $client = Client::query()->find($client->_id); + $client = Client::query()->find($client->id); $client->skillsWithCustomKeys()->sync($collection); $this->assertCount(2, $client->skillsWithCustomKeys); self::assertIsString($skill1->cskill_id); self::assertContains($skill1->cskill_id, $client->skillsWithCustomKeys->pluck('cskill_id')); - self::assertNotContains($skill1->_id, $client->skillsWithCustomKeys->pluck('cskill_id')); + self::assertNotContains($skill1->id, $client->skillsWithCustomKeys->pluck('cskill_id')); self::assertIsString($skill2->cskill_id); self::assertContains($skill2->cskill_id, $client->skillsWithCustomKeys->pluck('cskill_id')); - self::assertNotContains($skill2->_id, $client->skillsWithCustomKeys->pluck('cskill_id')); + self::assertNotContains($skill2->id, $client->skillsWithCustomKeys->pluck('cskill_id')); - $check = Skill::query()->find($skill1->_id); + $check = Skill::query()->find($skill1->id); self::assertIsString($check->cskill_id); self::assertContains($check->cskill_id, $client->skillsWithCustomKeys->pluck('cskill_id')); - self::assertNotContains($check->_id, $client->skillsWithCustomKeys->pluck('cskill_id')); + self::assertNotContains($check->id, $client->skillsWithCustomKeys->pluck('cskill_id')); - $check = Skill::query()->find($skill2->_id); + $check = Skill::query()->find($skill2->id); self::assertIsString($check->cskill_id); self::assertContains($check->cskill_id, $client->skillsWithCustomKeys->pluck('cskill_id')); - self::assertNotContains($check->_id, $client->skillsWithCustomKeys->pluck('cskill_id')); + self::assertNotContains($check->id, $client->skillsWithCustomKeys->pluck('cskill_id')); } public function testBelongsToManyAttachWithCustomKeys(): void @@ -431,27 +431,27 @@ public function testBelongsToManyAttachWithCustomKeys(): void $skill1 = Skill::create(['cskill_id' => (string) (new ObjectId()), 'name' => 'PHP']); $skill2 = Skill::create(['cskill_id' => (string) (new ObjectId()), 'name' => 'Laravel']); - $client = Client::query()->find($client->_id); + $client = Client::query()->find($client->id); $client->skillsWithCustomKeys()->attach([$skill1->cskill_id, $skill2->cskill_id]); $this->assertCount(2, $client->skillsWithCustomKeys); self::assertIsString($skill1->cskill_id); self::assertContains($skill1->cskill_id, $client->skillsWithCustomKeys->pluck('cskill_id')); - self::assertNotContains($skill1->_id, $client->skillsWithCustomKeys->pluck('cskill_id')); + self::assertNotContains($skill1->id, $client->skillsWithCustomKeys->pluck('cskill_id')); self::assertIsString($skill2->cskill_id); self::assertContains($skill2->cskill_id, $client->skillsWithCustomKeys->pluck('cskill_id')); - self::assertNotContains($skill2->_id, $client->skillsWithCustomKeys->pluck('cskill_id')); + self::assertNotContains($skill2->id, $client->skillsWithCustomKeys->pluck('cskill_id')); - $check = Skill::query()->find($skill1->_id); + $check = Skill::query()->find($skill1->id); self::assertIsString($check->cskill_id); self::assertContains($check->cskill_id, $client->skillsWithCustomKeys->pluck('cskill_id')); - self::assertNotContains($check->_id, $client->skillsWithCustomKeys->pluck('cskill_id')); + self::assertNotContains($check->id, $client->skillsWithCustomKeys->pluck('cskill_id')); - $check = Skill::query()->find($skill2->_id); + $check = Skill::query()->find($skill2->id); self::assertIsString($check->cskill_id); self::assertContains($check->cskill_id, $client->skillsWithCustomKeys->pluck('cskill_id')); - self::assertNotContains($check->_id, $client->skillsWithCustomKeys->pluck('cskill_id')); + self::assertNotContains($check->id, $client->skillsWithCustomKeys->pluck('cskill_id')); } public function testBelongsToManyAttachModelWithCustomKeys(): void @@ -459,18 +459,18 @@ public function testBelongsToManyAttachModelWithCustomKeys(): void $client = Client::create(['cclient_id' => (string) (new ObjectId()), 'years' => '5']); $skill1 = Skill::create(['cskill_id' => (string) (new ObjectId()), 'name' => 'PHP']); - $client = Client::query()->find($client->_id); + $client = Client::query()->find($client->id); $client->skillsWithCustomKeys()->attach($skill1); $this->assertCount(1, $client->skillsWithCustomKeys); self::assertIsString($skill1->cskill_id); self::assertContains($skill1->cskill_id, $client->skillsWithCustomKeys->pluck('cskill_id')); - self::assertNotContains($skill1->_id, $client->skillsWithCustomKeys->pluck('cskill_id')); + self::assertNotContains($skill1->id, $client->skillsWithCustomKeys->pluck('cskill_id')); - $check = Skill::query()->find($skill1->_id); - self::assertIsString($check->_id); + $check = Skill::query()->find($skill1->id); + self::assertIsString($check->id); self::assertContains($check->cskill_id, $client->skillsWithCustomKeys->pluck('cskill_id')); - self::assertNotContains($check->_id, $client->skillsWithCustomKeys->pluck('cskill_id')); + self::assertNotContains($check->id, $client->skillsWithCustomKeys->pluck('cskill_id')); } public function testBelongsToManyAttachEloquentCollectionWithCustomKeys(): void @@ -480,27 +480,27 @@ public function testBelongsToManyAttachEloquentCollectionWithCustomKeys(): void $skill2 = Skill::create(['cskill_id' => (string) (new ObjectId()), 'name' => 'Laravel']); $collection = new Collection([$skill1, $skill2]); - $client = Client::query()->find($client->_id); + $client = Client::query()->find($client->id); $client->skillsWithCustomKeys()->attach($collection); $this->assertCount(2, $client->skillsWithCustomKeys); self::assertIsString($skill1->cskill_id); self::assertContains($skill1->cskill_id, $client->skillsWithCustomKeys->pluck('cskill_id')); - self::assertNotContains($skill1->_id, $client->skillsWithCustomKeys->pluck('cskill_id')); + self::assertNotContains($skill1->id, $client->skillsWithCustomKeys->pluck('cskill_id')); self::assertIsString($skill2->cskill_id); self::assertContains($skill2->cskill_id, $client->skillsWithCustomKeys->pluck('cskill_id')); - self::assertNotContains($skill2->_id, $client->skillsWithCustomKeys->pluck('cskill_id')); + self::assertNotContains($skill2->id, $client->skillsWithCustomKeys->pluck('cskill_id')); - $check = Skill::query()->find($skill1->_id); + $check = Skill::query()->find($skill1->id); self::assertIsString($check->cskill_id); self::assertContains($check->cskill_id, $client->skillsWithCustomKeys->pluck('cskill_id')); - self::assertNotContains($check->_id, $client->skillsWithCustomKeys->pluck('cskill_id')); + self::assertNotContains($check->id, $client->skillsWithCustomKeys->pluck('cskill_id')); - $check = Skill::query()->find($skill2->_id); + $check = Skill::query()->find($skill2->id); self::assertIsString($check->cskill_id); self::assertContains($check->cskill_id, $client->skillsWithCustomKeys->pluck('cskill_id')); - self::assertNotContains($check->_id, $client->skillsWithCustomKeys->pluck('cskill_id')); + self::assertNotContains($check->id, $client->skillsWithCustomKeys->pluck('cskill_id')); } public function testBelongsToManyDetachWithCustomKeys(): void @@ -509,7 +509,7 @@ public function testBelongsToManyDetachWithCustomKeys(): void $skill1 = Skill::create(['cskill_id' => (string) (new ObjectId()), 'name' => 'PHP']); $skill2 = Skill::create(['cskill_id' => (string) (new ObjectId()), 'name' => 'Laravel']); - $client = Client::query()->find($client->_id); + $client = Client::query()->find($client->id); $client->skillsWithCustomKeys()->sync([$skill1->cskill_id, $skill2->cskill_id]); $this->assertCount(2, $client->skillsWithCustomKeys); @@ -519,21 +519,21 @@ public function testBelongsToManyDetachWithCustomKeys(): void self::assertIsString($skill1->cskill_id); self::assertNotContains($skill1->cskill_id, $client->skillsWithCustomKeys->pluck('cskill_id')); - self::assertNotContains($skill1->_id, $client->skillsWithCustomKeys->pluck('cskill_id')); + self::assertNotContains($skill1->id, $client->skillsWithCustomKeys->pluck('cskill_id')); self::assertIsString($skill2->cskill_id); self::assertContains($skill2->cskill_id, $client->skillsWithCustomKeys->pluck('cskill_id')); - self::assertNotContains($skill2->_id, $client->skillsWithCustomKeys->pluck('cskill_id')); + self::assertNotContains($skill2->id, $client->skillsWithCustomKeys->pluck('cskill_id')); - $check = Skill::query()->find($skill1->_id); + $check = Skill::query()->find($skill1->id); self::assertIsString($check->cskill_id); self::assertNotContains($check->cskill_id, $client->skillsWithCustomKeys->pluck('cskill_id')); - self::assertNotContains($check->_id, $client->skillsWithCustomKeys->pluck('cskill_id')); + self::assertNotContains($check->id, $client->skillsWithCustomKeys->pluck('cskill_id')); - $check = Skill::query()->find($skill2->_id); + $check = Skill::query()->find($skill2->id); self::assertIsString($check->cskill_id); self::assertContains($check->cskill_id, $client->skillsWithCustomKeys->pluck('cskill_id')); - self::assertNotContains($check->_id, $client->skillsWithCustomKeys->pluck('cskill_id')); + self::assertNotContains($check->id, $client->skillsWithCustomKeys->pluck('cskill_id')); } public function testBelongsToManyDetachModelWithCustomKeys(): void @@ -542,7 +542,7 @@ public function testBelongsToManyDetachModelWithCustomKeys(): void $skill1 = Skill::create(['cskill_id' => (string) (new ObjectId()), 'name' => 'PHP']); $skill2 = Skill::create(['cskill_id' => (string) (new ObjectId()), 'name' => 'Laravel']); - $client = Client::query()->find($client->_id); + $client = Client::query()->find($client->id); $client->skillsWithCustomKeys()->sync([$skill1->cskill_id, $skill2->cskill_id]); $this->assertCount(2, $client->skillsWithCustomKeys); @@ -552,28 +552,28 @@ public function testBelongsToManyDetachModelWithCustomKeys(): void self::assertIsString($skill1->cskill_id); self::assertNotContains($skill1->cskill_id, $client->skillsWithCustomKeys->pluck('cskill_id')); - self::assertNotContains($skill1->_id, $client->skillsWithCustomKeys->pluck('cskill_id')); + self::assertNotContains($skill1->id, $client->skillsWithCustomKeys->pluck('cskill_id')); self::assertIsString($skill2->cskill_id); self::assertContains($skill2->cskill_id, $client->skillsWithCustomKeys->pluck('cskill_id')); - self::assertNotContains($skill2->_id, $client->skillsWithCustomKeys->pluck('cskill_id')); + self::assertNotContains($skill2->id, $client->skillsWithCustomKeys->pluck('cskill_id')); - $check = Skill::query()->find($skill1->_id); + $check = Skill::query()->find($skill1->id); self::assertIsString($check->cskill_id); self::assertNotContains($check->cskill_id, $client->skillsWithCustomKeys->pluck('cskill_id')); - self::assertNotContains($check->_id, $client->skillsWithCustomKeys->pluck('cskill_id')); + self::assertNotContains($check->id, $client->skillsWithCustomKeys->pluck('cskill_id')); - $check = Skill::query()->find($skill2->_id); + $check = Skill::query()->find($skill2->id); self::assertIsString($check->cskill_id); self::assertContains($check->cskill_id, $client->skillsWithCustomKeys->pluck('cskill_id')); - self::assertNotContains($check->_id, $client->skillsWithCustomKeys->pluck('cskill_id')); + self::assertNotContains($check->id, $client->skillsWithCustomKeys->pluck('cskill_id')); } public function testBelongsToManySyncAlreadyPresent(): void { $user = User::create(['name' => 'John Doe']); - $client1 = Client::create(['name' => 'Test 1'])->_id; - $client2 = Client::create(['name' => 'Test 2'])->_id; + $client1 = Client::create(['name' => 'Test 1'])->id; + $client2 = Client::create(['name' => 'Test 2'])->id; $user->clients()->sync([$client1, $client2]); $this->assertCount(2, $user->clients); @@ -592,18 +592,18 @@ public function testBelongsToManyCustom(): void $group = $user->groups()->create(['name' => 'Admins']); // Refetch - $user = User::find($user->_id); - $group = Group::find($group->_id); + $user = User::find($user->id); + $group = Group::find($group->id); // Check for custom relation attributes $this->assertArrayHasKey('users', $group->getAttributes()); $this->assertArrayHasKey('groups', $user->getAttributes()); // Assert they are attached - $this->assertContains($group->_id, $user->groups->pluck('_id')->toArray()); - $this->assertContains($user->_id, $group->users->pluck('_id')->toArray()); - $this->assertEquals($group->_id, $user->groups()->first()->_id); - $this->assertEquals($user->_id, $group->users()->first()->_id); + $this->assertContains($group->id, $user->groups->pluck('id')->toArray()); + $this->assertContains($user->id, $group->users->pluck('id')->toArray()); + $this->assertEquals($group->id, $user->groups()->first()->id); + $this->assertEquals($user->id, $group->users()->first()->id); } public function testMorph(): void @@ -617,7 +617,7 @@ public function testMorph(): void $this->assertEquals(1, $user->photos->count()); $this->assertEquals($photo->id, $user->photos->first()->id); - $user = User::find($user->_id); + $user = User::find($user->id); $this->assertEquals(1, $user->photos->count()); $this->assertEquals($photo->id, $user->photos->first()->id); @@ -627,14 +627,14 @@ public function testMorph(): void $this->assertNotNull($client->photo); $this->assertEquals($photo->id, $client->photo->id); - $client = Client::find($client->_id); + $client = Client::find($client->id); $this->assertNotNull($client->photo); $this->assertEquals($photo->id, $client->photo->id); $photo = Photo::first(); $this->assertEquals($photo->hasImage->name, $user->name); - $user = User::with('photos')->find($user->_id); + $user = User::with('photos')->find($user->id); $relations = $user->getRelations(); $this->assertArrayHasKey('photos', $relations); $this->assertEquals(1, $relations['photos']->count()); @@ -655,7 +655,7 @@ public function testMorph(): void $this->assertCount(1, $photo->hasImage()->get()); $this->assertInstanceOf(Client::class, $photo->hasImage); - $this->assertEquals($client->_id, $photo->hasImage->_id); + $this->assertEquals($client->id, $photo->hasImage->id); // inverse with custom ownerKey $photo = Photo::query()->create(['url' => 'https://graph.facebook.com/young.gerald/picture']); @@ -665,7 +665,7 @@ public function testMorph(): void $this->assertCount(1, $photo->hasImageWithCustomOwnerKey()->get()); $this->assertInstanceOf(Client::class, $photo->hasImageWithCustomOwnerKey); $this->assertEquals($client->cclient_id, $photo->has_image_with_custom_owner_key_id); - $this->assertEquals($client->_id, $photo->hasImageWithCustomOwnerKey->_id); + $this->assertEquals($client->id, $photo->hasImageWithCustomOwnerKey->id); } public function testMorphToMany(): void @@ -679,10 +679,10 @@ public function testMorphToMany(): void $client->labels()->attach($label); $this->assertEquals(1, $user->labels->count()); - $this->assertContains($label->_id, $user->labels->pluck('_id')); + $this->assertContains($label->id, $user->labels->pluck('id')); $this->assertEquals(1, $client->labels->count()); - $this->assertContains($label->_id, $user->labels->pluck('_id')); + $this->assertContains($label->id, $user->labels->pluck('id')); } public function testMorphToManyAttachEloquentCollection(): void @@ -695,8 +695,8 @@ public function testMorphToManyAttachEloquentCollection(): void $client->labels()->attach(new Collection([$label1, $label2])); $this->assertEquals(2, $client->labels->count()); - $this->assertContains($label1->_id, $client->labels->pluck('_id')); - $this->assertContains($label2->_id, $client->labels->pluck('_id')); + $this->assertContains($label1->id, $client->labels->pluck('id')); + $this->assertContains($label2->id, $client->labels->pluck('id')); } public function testMorphToManyAttachMultipleIds(): void @@ -706,11 +706,11 @@ public function testMorphToManyAttachMultipleIds(): void $label1 = Label::query()->create(['name' => 'stayed solid i never fled']); $label2 = Label::query()->create(['name' => "I've got a lane and I'm in gear"]); - $client->labels()->attach([$label1->_id, $label2->_id]); + $client->labels()->attach([$label1->id, $label2->id]); $this->assertEquals(2, $client->labels->count()); - $this->assertContains($label1->_id, $client->labels->pluck('_id')); - $this->assertContains($label2->_id, $client->labels->pluck('_id')); + $this->assertContains($label1->id, $client->labels->pluck('id')); + $this->assertContains($label2->id, $client->labels->pluck('id')); } public function testMorphToManyDetaching(): void @@ -720,7 +720,7 @@ public function testMorphToManyDetaching(): void $label1 = Label::query()->create(['name' => "I'll never love again"]); $label2 = Label::query()->create(['name' => 'The way I loved you']); - $client->labels()->attach([$label1->_id, $label2->_id]); + $client->labels()->attach([$label1->id, $label2->id]); $this->assertEquals(2, $client->labels->count()); @@ -728,7 +728,7 @@ public function testMorphToManyDetaching(): void $check = $client->withoutRelations(); $this->assertEquals(1, $check->labels->count()); - $this->assertContains($label2->_id, $client->labels->pluck('_id')); + $this->assertContains($label2->id, $client->labels->pluck('id')); } public function testMorphToManyDetachingMultipleIds(): void @@ -739,15 +739,15 @@ public function testMorphToManyDetachingMultipleIds(): void $label2 = Label::query()->create(['name' => "My skin's thick, but I'm not bulletproof"]); $label3 = Label::query()->create(['name' => 'All I can be is myself, go, and tell the truth']); - $client->labels()->attach([$label1->_id, $label2->_id, $label3->_id]); + $client->labels()->attach([$label1->id, $label2->id, $label3->id]); $this->assertEquals(3, $client->labels->count()); - $client->labels()->detach([$label1->_id, $label2->_id]); + $client->labels()->detach([$label1->id, $label2->id]); $client->refresh(); $this->assertEquals(1, $client->labels->count()); - $this->assertContains($label3->_id, $client->labels->pluck('_id')); + $this->assertContains($label3->id, $client->labels->pluck('id')); } public function testMorphToManySyncing(): void @@ -763,12 +763,12 @@ public function testMorphToManySyncing(): void $client->labels()->sync($label2, false); $this->assertEquals(1, $user->labels->count()); - $this->assertContains($label->_id, $user->labels->pluck('_id')); - $this->assertNotContains($label2->_id, $user->labels->pluck('_id')); + $this->assertContains($label->id, $user->labels->pluck('id')); + $this->assertNotContains($label2->id, $user->labels->pluck('id')); $this->assertEquals(2, $client->labels->count()); - $this->assertContains($label->_id, $client->labels->pluck('_id')); - $this->assertContains($label2->_id, $client->labels->pluck('_id')); + $this->assertContains($label->id, $client->labels->pluck('id')); + $this->assertContains($label2->id, $client->labels->pluck('id')); } public function testMorphToManySyncingEloquentCollection(): void @@ -781,8 +781,8 @@ public function testMorphToManySyncingEloquentCollection(): void $client->labels()->sync(new Collection([$label, $label2])); $this->assertEquals(2, $client->labels->count()); - $this->assertContains($label->_id, $client->labels->pluck('_id')); - $this->assertContains($label2->_id, $client->labels->pluck('_id')); + $this->assertContains($label->id, $client->labels->pluck('id')); + $this->assertContains($label2->id, $client->labels->pluck('id')); } public function testMorphToManySyncingMultipleIds(): void @@ -792,11 +792,11 @@ public function testMorphToManySyncingMultipleIds(): void $label = Label::query()->create(['name' => 'They all talk about karma, how it slowly comes']); $label2 = Label::query()->create(['name' => "But life is short, enjoy it while you're young"]); - $client->labels()->sync([$label->_id, $label2->_id]); + $client->labels()->sync([$label->id, $label2->id]); $this->assertEquals(2, $client->labels->count()); - $this->assertContains($label->_id, $client->labels->pluck('_id')); - $this->assertContains($label2->_id, $client->labels->pluck('_id')); + $this->assertContains($label->id, $client->labels->pluck('id')); + $this->assertContains($label2->id, $client->labels->pluck('id')); } public function testMorphToManySyncingWithCustomKeys(): void @@ -809,15 +809,15 @@ public function testMorphToManySyncingWithCustomKeys(): void $client->labelsWithCustomKeys()->sync([$label->clabel_id, $label2->clabel_id]); $this->assertEquals(2, $client->labelsWithCustomKeys->count()); - $this->assertContains($label->_id, $client->labelsWithCustomKeys->pluck('_id')); - $this->assertContains($label2->_id, $client->labelsWithCustomKeys->pluck('_id')); + $this->assertContains($label->id, $client->labelsWithCustomKeys->pluck('id')); + $this->assertContains($label2->id, $client->labelsWithCustomKeys->pluck('id')); $client->labelsWithCustomKeys()->sync($label); $client->load('labelsWithCustomKeys'); $this->assertEquals(1, $client->labelsWithCustomKeys->count()); - $this->assertContains($label->_id, $client->labelsWithCustomKeys->pluck('_id')); - $this->assertNotContains($label2->_id, $client->labelsWithCustomKeys->pluck('_id')); + $this->assertContains($label->id, $client->labelsWithCustomKeys->pluck('id')); + $this->assertNotContains($label2->id, $client->labelsWithCustomKeys->pluck('id')); } public function testMorphToManyLoadAndRefreshing(): void @@ -829,7 +829,7 @@ public function testMorphToManyLoadAndRefreshing(): void $label = Label::query()->create(['name' => 'The greatest gift is knowledge itself']); $label2 = Label::query()->create(['name' => "I made it here all by my lonely, no askin' for help"]); - $client->labels()->sync([$label->_id, $label2->_id]); + $client->labels()->sync([$label->id, $label2->id]); $client->users()->sync($user); $this->assertEquals(2, $client->labels->count()); @@ -842,11 +842,11 @@ public function testMorphToManyLoadAndRefreshing(): void $this->assertEquals(2, $client->labels->count()); - $check = Client::query()->find($client->_id); + $check = Client::query()->find($client->id); $this->assertEquals(2, $check->labels->count()); - $check = Client::query()->with('labels')->find($client->_id); + $check = Client::query()->with('labels')->find($client->id); $this->assertEquals(2, $check->labels->count()); } @@ -860,7 +860,7 @@ public function testMorphToManyHasQuery(): void $label = Label::query()->create(['name' => "I've been digging myself down deeper"]); $label2 = Label::query()->create(['name' => "I won't stop 'til I get where you are"]); - $client->labels()->sync([$label->_id, $label2->_id]); + $client->labels()->sync([$label->id, $label2->id]); $client2->labels()->sync($label); $this->assertEquals(2, $client->labels->count()); @@ -871,12 +871,12 @@ public function testMorphToManyHasQuery(): void $check = Client::query()->has('labels', '>', 1)->get(); $this->assertCount(1, $check); - $this->assertContains($client->_id, $check->pluck('_id')); + $this->assertContains($client->id, $check->pluck('id')); $check = Client::query()->has('labels', '<', 2)->get(); $this->assertCount(2, $check); - $this->assertContains($client2->_id, $check->pluck('_id')); - $this->assertContains($client3->_id, $check->pluck('_id')); + $this->assertContains($client2->id, $check->pluck('id')); + $this->assertContains($client3->id, $check->pluck('id')); } public function testMorphedByMany(): void @@ -891,10 +891,10 @@ public function testMorphedByMany(): void $label->clients()->attach($client); $this->assertEquals(1, $label->users->count()); - $this->assertContains($user->_id, $label->users->pluck('_id')); + $this->assertContains($user->id, $label->users->pluck('id')); $this->assertEquals(1, $label->clients->count()); - $this->assertContains($client->_id, $label->clients->pluck('_id')); + $this->assertContains($client->id, $label->clients->pluck('id')); } public function testMorphedByManyAttachEloquentCollection(): void @@ -908,8 +908,8 @@ public function testMorphedByManyAttachEloquentCollection(): void $label->clients()->attach(new Collection([$client1, $client2])); $this->assertEquals(2, $label->clients->count()); - $this->assertContains($client1->_id, $label->clients->pluck('_id')); - $this->assertContains($client2->_id, $label->clients->pluck('_id')); + $this->assertContains($client1->id, $label->clients->pluck('id')); + $this->assertContains($client2->id, $label->clients->pluck('id')); $client1->refresh(); $this->assertEquals(1, $client1->labels->count()); @@ -923,11 +923,11 @@ public function testMorphedByManyAttachMultipleIds(): void $label = Label::query()->create(['name' => 'Always in the game and never played by the rules']); - $label->clients()->attach([$client1->_id, $client2->_id]); + $label->clients()->attach([$client1->id, $client2->id]); $this->assertEquals(2, $label->clients->count()); - $this->assertContains($client1->_id, $label->clients->pluck('_id')); - $this->assertContains($client2->_id, $label->clients->pluck('_id')); + $this->assertContains($client1->id, $label->clients->pluck('id')); + $this->assertContains($client2->id, $label->clients->pluck('id')); $client1->refresh(); $this->assertEquals(1, $client1->labels->count()); @@ -941,15 +941,15 @@ public function testMorphedByManyDetaching(): void $label = Label::query()->create(['name' => 'Seasons change and our love went cold']); - $label->clients()->attach([$client1->_id, $client2->_id]); + $label->clients()->attach([$client1->id, $client2->id]); $this->assertEquals(2, $label->clients->count()); - $label->clients()->detach($client1->_id); + $label->clients()->detach($client1->id); $check = $label->withoutRelations(); $this->assertEquals(1, $check->clients->count()); - $this->assertContains($client2->_id, $check->clients->pluck('_id')); + $this->assertContains($client2->id, $check->clients->pluck('id')); } public function testMorphedByManyDetachingMultipleIds(): void @@ -960,15 +960,15 @@ public function testMorphedByManyDetachingMultipleIds(): void $label = Label::query()->create(['name' => "Run away, but we're running in circles"]); - $label->clients()->attach([$client1->_id, $client2->_id, $client3->_id]); + $label->clients()->attach([$client1->id, $client2->id, $client3->id]); $this->assertEquals(3, $label->clients->count()); - $label->clients()->detach([$client1->_id, $client2->_id]); + $label->clients()->detach([$client1->id, $client2->id]); $label->load('clients'); $this->assertEquals(1, $label->clients->count()); - $this->assertContains($client3->_id, $label->clients->pluck('_id')); + $this->assertContains($client3->id, $label->clients->pluck('id')); } public function testMorphedByManySyncing(): void @@ -984,9 +984,9 @@ public function testMorphedByManySyncing(): void $label->clients()->sync($client3, false); $this->assertEquals(3, $label->clients->count()); - $this->assertContains($client1->_id, $label->clients->pluck('_id')); - $this->assertContains($client2->_id, $label->clients->pluck('_id')); - $this->assertContains($client3->_id, $label->clients->pluck('_id')); + $this->assertContains($client1->id, $label->clients->pluck('id')); + $this->assertContains($client2->id, $label->clients->pluck('id')); + $this->assertContains($client3->id, $label->clients->pluck('id')); } public function testMorphedByManySyncingEloquentCollection(): void @@ -1000,10 +1000,10 @@ public function testMorphedByManySyncingEloquentCollection(): void $label->clients()->sync(new Collection([$client1, $client2])); $this->assertEquals(2, $label->clients->count()); - $this->assertContains($client1->_id, $label->clients->pluck('_id')); - $this->assertContains($client2->_id, $label->clients->pluck('_id')); + $this->assertContains($client1->id, $label->clients->pluck('id')); + $this->assertContains($client2->id, $label->clients->pluck('id')); - $this->assertNotContains($extra->_id, $label->clients->pluck('_id')); + $this->assertNotContains($extra->id, $label->clients->pluck('id')); } public function testMorphedByManySyncingMultipleIds(): void @@ -1014,13 +1014,13 @@ public function testMorphedByManySyncingMultipleIds(): void $label = Label::query()->create(['name' => "Love ain't patient, it's not kind. true love waits to rob you blind"]); - $label->clients()->sync([$client1->_id, $client2->_id]); + $label->clients()->sync([$client1->id, $client2->id]); $this->assertEquals(2, $label->clients->count()); - $this->assertContains($client1->_id, $label->clients->pluck('_id')); - $this->assertContains($client2->_id, $label->clients->pluck('_id')); + $this->assertContains($client1->id, $label->clients->pluck('id')); + $this->assertContains($client2->id, $label->clients->pluck('id')); - $this->assertNotContains($extra->_id, $label->clients->pluck('_id')); + $this->assertNotContains($extra->id, $label->clients->pluck('id')); } public function testMorphedByManySyncingWithCustomKeys(): void @@ -1034,19 +1034,19 @@ public function testMorphedByManySyncingWithCustomKeys(): void $label->clientsWithCustomKeys()->sync([$client1->cclient_id, $client2->cclient_id]); $this->assertEquals(2, $label->clientsWithCustomKeys->count()); - $this->assertContains($client1->_id, $label->clientsWithCustomKeys->pluck('_id')); - $this->assertContains($client2->_id, $label->clientsWithCustomKeys->pluck('_id')); + $this->assertContains($client1->id, $label->clientsWithCustomKeys->pluck('id')); + $this->assertContains($client2->id, $label->clientsWithCustomKeys->pluck('id')); - $this->assertNotContains($client3->_id, $label->clientsWithCustomKeys->pluck('_id')); + $this->assertNotContains($client3->id, $label->clientsWithCustomKeys->pluck('id')); $label->clientsWithCustomKeys()->sync($client3); $label->load('clientsWithCustomKeys'); $this->assertEquals(1, $label->clientsWithCustomKeys->count()); - $this->assertNotContains($client1->_id, $label->clientsWithCustomKeys->pluck('_id')); - $this->assertNotContains($client2->_id, $label->clientsWithCustomKeys->pluck('_id')); + $this->assertNotContains($client1->id, $label->clientsWithCustomKeys->pluck('id')); + $this->assertNotContains($client2->id, $label->clientsWithCustomKeys->pluck('id')); - $this->assertContains($client3->_id, $label->clientsWithCustomKeys->pluck('_id')); + $this->assertContains($client3->id, $label->clientsWithCustomKeys->pluck('id')); } public function testMorphedByManyLoadAndRefreshing(): void @@ -1072,11 +1072,11 @@ public function testMorphedByManyLoadAndRefreshing(): void $this->assertEquals(3, $label->clients->count()); - $check = Label::query()->find($label->_id); + $check = Label::query()->find($label->id); $this->assertEquals(3, $check->clients->count()); - $check = Label::query()->with('clients')->find($label->_id); + $check = Label::query()->with('clients')->find($label->id); $this->assertEquals(3, $check->clients->count()); } @@ -1100,16 +1100,16 @@ public function testMorphedByManyHasQuery(): void $check = Label::query()->has('clients')->get(); $this->assertCount(2, $check); - $this->assertContains($label->_id, $check->pluck('_id')); - $this->assertContains($label2->_id, $check->pluck('_id')); + $this->assertContains($label->id, $check->pluck('id')); + $this->assertContains($label2->id, $check->pluck('id')); $check = Label::query()->has('users')->get(); $this->assertCount(1, $check); - $this->assertContains($label3->_id, $check->pluck('_id')); + $this->assertContains($label3->id, $check->pluck('id')); $check = Label::query()->has('clients', '>', 1)->get(); $this->assertCount(1, $check); - $this->assertContains($label->_id, $check->pluck('_id')); + $this->assertContains($label->id, $check->pluck('id')); } public function testHasManyHas(): void @@ -1219,18 +1219,18 @@ public function testDoubleSaveOneToMany(): void $author->books()->save($book); $author->save(); $this->assertEquals(1, $author->books()->count()); - $this->assertEquals($author->_id, $book->author_id); + $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); + $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); + $this->assertEquals($author->id, $book->author_id); } public function testDoubleSaveManyToMany(): void @@ -1243,29 +1243,29 @@ public function testDoubleSaveManyToMany(): void $user->save(); $this->assertEquals(1, $user->clients()->count()); - $this->assertEquals([$user->_id], $client->user_ids); - $this->assertEquals([$client->_id], $user->client_ids); + $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); + $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); + $this->assertEquals([$user->id], $client->user_ids); + $this->assertEquals([$client->id], $user->client_ids); } public function testWhereBelongsTo() { $user = User::create(['name' => 'John Doe']); - Item::create(['user_id' => $user->_id]); - Item::create(['user_id' => $user->_id]); - Item::create(['user_id' => $user->_id]); + Item::create(['user_id' => $user->id]); + Item::create(['user_id' => $user->id]); + Item::create(['user_id' => $user->id]); Item::create(['user_id' => null]); $items = Item::whereBelongsTo($user)->get(); diff --git a/tests/SchemaTest.php b/tests/SchemaTest.php index 6e6248beb..aba1816cd 100644 --- a/tests/SchemaTest.php +++ b/tests/SchemaTest.php @@ -346,15 +346,15 @@ public function testRenameColumn(): void $check = DB::connection()->collection('newcollection')->get(); $this->assertCount(3, $check); - $this->assertArrayHasKey('test', $check[0]); - $this->assertArrayNotHasKey('newtest', $check[0]); + $this->assertObjectHasProperty('test', $check[0]); + $this->assertObjectNotHasProperty('newtest', $check[0]); - $this->assertArrayHasKey('test', $check[1]); - $this->assertArrayNotHasKey('newtest', $check[1]); + $this->assertObjectHasProperty('test', $check[1]); + $this->assertObjectNotHasProperty('newtest', $check[1]); - $this->assertArrayHasKey('column', $check[2]); - $this->assertArrayNotHasKey('test', $check[2]); - $this->assertArrayNotHasKey('newtest', $check[2]); + $this->assertObjectHasProperty('column', $check[2]); + $this->assertObjectNotHasProperty('test', $check[2]); + $this->assertObjectNotHasProperty('newtest', $check[2]); Schema::collection('newcollection', function (Blueprint $collection) { $collection->renameColumn('test', 'newtest'); @@ -363,18 +363,18 @@ public function testRenameColumn(): void $check2 = DB::connection()->collection('newcollection')->get(); $this->assertCount(3, $check2); - $this->assertArrayHasKey('newtest', $check2[0]); - $this->assertArrayNotHasKey('test', $check2[0]); - $this->assertSame($check[0]['test'], $check2[0]['newtest']); + $this->assertObjectHasProperty('newtest', $check2[0]); + $this->assertObjectNotHasProperty('test', $check2[0]); + $this->assertSame($check[0]->test, $check2[0]->newtest); - $this->assertArrayHasKey('newtest', $check2[1]); - $this->assertArrayNotHasKey('test', $check2[1]); - $this->assertSame($check[1]['test'], $check2[1]['newtest']); + $this->assertObjectHasProperty('newtest', $check2[1]); + $this->assertObjectNotHasProperty('test', $check2[1]); + $this->assertSame($check[1]->test, $check2[1]->newtest); - $this->assertArrayHasKey('column', $check2[2]); - $this->assertArrayNotHasKey('test', $check2[2]); - $this->assertArrayNotHasKey('newtest', $check2[2]); - $this->assertSame($check[2]['column'], $check2[2]['column']); + $this->assertObjectHasProperty('column', $check2[2]); + $this->assertObjectNotHasProperty('test', $check2[2]); + $this->assertObjectNotHasProperty('newtest', $check2[2]); + $this->assertSame($check[2]->column, $check2[2]->column); } protected function getIndex(string $collection, string $name) diff --git a/tests/SchemaVersionTest.php b/tests/SchemaVersionTest.php index dfe2f5122..0f4223975 100644 --- a/tests/SchemaVersionTest.php +++ b/tests/SchemaVersionTest.php @@ -42,7 +42,7 @@ public function testWithBasicDocument() ->where('name', 'Vador') ->get(); - $this->assertEquals(2, $data[0]['schema_version']); + $this->assertEquals(2, $data[0]->schema_version); } public function testIncompleteImplementation(): void diff --git a/tests/Ticket/GH2783Test.php b/tests/Ticket/GH2783Test.php index 73324ddc0..f1580c1e6 100644 --- a/tests/Ticket/GH2783Test.php +++ b/tests/Ticket/GH2783Test.php @@ -32,7 +32,7 @@ public function testMorphToInfersCustomOwnerKey() $queriedImageWithPost = GH2783Image::with('imageable')->find($imageWithPost->getKey()); $this->assertInstanceOf(GH2783Post::class, $queriedImageWithPost->imageable); - $this->assertEquals($post->_id, $queriedImageWithPost->imageable->getKey()); + $this->assertEquals($post->id, $queriedImageWithPost->imageable->getKey()); $queriedImageWithUser = GH2783Image::with('imageable')->find($imageWithUser->getKey()); $this->assertInstanceOf(GH2783User::class, $queriedImageWithUser->imageable); diff --git a/tests/TransactionTest.php b/tests/TransactionTest.php index 3338c6832..411eb226c 100644 --- a/tests/TransactionTest.php +++ b/tests/TransactionTest.php @@ -44,7 +44,7 @@ public function testCreateWithCommit(): void $this->assertTrue($klinson->exists); $this->assertEquals('klinson', $klinson->name); - $check = User::find($klinson->_id); + $check = User::find($klinson->id); $this->assertInstanceOf(User::class, $check); $this->assertEquals($klinson->name, $check->name); } @@ -60,7 +60,7 @@ public function testCreateRollBack(): void $this->assertTrue($klinson->exists); $this->assertEquals('klinson', $klinson->name); - $this->assertFalse(User::where('_id', $klinson->_id)->exists()); + $this->assertFalse(User::where('id', $klinson->id)->exists()); } public function testInsertWithCommit(): void @@ -93,7 +93,7 @@ public function testEloquentCreateWithCommit(): void $this->assertTrue($klinson->exists); $this->assertNotNull($klinson->getIdAttribute()); - $check = User::find($klinson->_id); + $check = User::find($klinson->id); $this->assertInstanceOf(User::class, $check); $this->assertEquals($check->name, $klinson->name); } @@ -110,7 +110,7 @@ public function testEloquentCreateWithRollBack(): void $this->assertTrue($klinson->exists); $this->assertNotNull($klinson->getIdAttribute()); - $this->assertFalse(User::where('_id', $klinson->_id)->exists()); + $this->assertFalse(User::where('id', $klinson->id)->exists()); } public function testInsertGetIdWithCommit(): void @@ -122,7 +122,7 @@ public function testInsertGetIdWithCommit(): void $this->assertInstanceOf(ObjectId::class, $userId); $user = DB::collection('users')->find((string) $userId); - $this->assertEquals('klinson', $user['name']); + $this->assertEquals('klinson', $user->name); } public function testInsertGetIdWithRollBack(): void @@ -132,7 +132,7 @@ public function testInsertGetIdWithRollBack(): void DB::rollBack(); $this->assertInstanceOf(ObjectId::class, $userId); - $this->assertFalse(DB::collection('users')->where('_id', (string) $userId)->exists()); + $this->assertFalse(DB::collection('users')->where('id', (string) $userId)->exists()); } public function testUpdateWithCommit(): void @@ -176,8 +176,8 @@ public function testEloquentUpdateWithCommit(): void $this->assertEquals(21, $klinson->age); $this->assertEquals(39, $alcaeus->age); - $this->assertTrue(User::where('_id', $klinson->_id)->where('age', 21)->exists()); - $this->assertTrue(User::where('_id', $alcaeus->_id)->where('age', 39)->exists()); + $this->assertTrue(User::where('id', $klinson->id)->where('age', 21)->exists()); + $this->assertTrue(User::where('id', $alcaeus->id)->where('age', 39)->exists()); } public function testEloquentUpdateWithRollBack(): void @@ -197,8 +197,8 @@ public function testEloquentUpdateWithRollBack(): void $this->assertEquals(21, $klinson->age); $this->assertEquals(39, $alcaeus->age); - $this->assertFalse(User::where('_id', $klinson->_id)->where('age', 21)->exists()); - $this->assertFalse(User::where('_id', $alcaeus->_id)->where('age', 39)->exists()); + $this->assertFalse(User::where('id', $klinson->id)->where('age', 21)->exists()); + $this->assertFalse(User::where('id', $alcaeus->id)->where('age', 39)->exists()); } public function testDeleteWithCommit(): void @@ -234,7 +234,7 @@ public function testEloquentDeleteWithCommit(): void $klinson->delete(); DB::commit(); - $this->assertFalse(User::where('_id', $klinson->_id)->exists()); + $this->assertFalse(User::where('id', $klinson->id)->exists()); } public function testEloquentDeleteWithRollBack(): void @@ -246,7 +246,7 @@ public function testEloquentDeleteWithRollBack(): void $klinson->delete(); DB::rollBack(); - $this->assertTrue(User::where('_id', $klinson->_id)->exists()); + $this->assertTrue(User::where('id', $klinson->id)->exists()); } public function testIncrementWithCommit(): void @@ -390,7 +390,7 @@ public function testTransactionRespectsRepetitionLimit(): void $this->assertSame(2, $timesRun); - $check = User::find($klinson->_id); + $check = User::find($klinson->id); $this->assertInstanceOf(User::class, $check); // Age is expected to be 24: the callback is executed twice, incrementing age by 2 every time From 6a05d692a738c7bc13249e2a2e6a91bab6224312 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=A9r=C3=B4me=20Tamarelle?= Date: Fri, 12 Jul 2024 10:09:01 +0200 Subject: [PATCH 08/10] Remove class MongoFailedJobProvider --- src/Collection.php | 1 - src/MongoDBQueueServiceProvider.php | 5 ----- src/Query/Builder.php | 2 +- src/Queue/Failed/MongoFailedJobProvider.php | 12 ------------ tests/Query/AggregationBuilderTest.php | 3 ++- tests/QueryBuilderTest.php | 1 - ...derTest.php => DatabaseFailedJobProviderTest.php} | 11 +++++++---- tests/QueueTest.php | 2 -- 8 files changed, 10 insertions(+), 27 deletions(-) delete mode 100644 src/Queue/Failed/MongoFailedJobProvider.php rename tests/Queue/Failed/{MongoFailedJobProviderTest.php => DatabaseFailedJobProviderTest.php} (92%) diff --git a/src/Collection.php b/src/Collection.php index e78fdea6e..22c0dfa05 100644 --- a/src/Collection.php +++ b/src/Collection.php @@ -6,7 +6,6 @@ use Exception; use MongoDB\BSON\ObjectID; -use MongoDB\BSON\UTCDateTime; use MongoDB\Collection as MongoCollection; use function array_walk_recursive; diff --git a/src/MongoDBQueueServiceProvider.php b/src/MongoDBQueueServiceProvider.php index 1b7bf2ca3..3a930bcba 100644 --- a/src/MongoDBQueueServiceProvider.php +++ b/src/MongoDBQueueServiceProvider.php @@ -7,12 +7,8 @@ use Illuminate\Queue\Failed\DatabaseFailedJobProvider; use Illuminate\Queue\Failed\NullFailedJobProvider; use Illuminate\Queue\QueueServiceProvider; -use MongoDB\Laravel\Queue\Failed\MongoFailedJobProvider; use function array_key_exists; -use function trigger_error; - -use const E_USER_DEPRECATED; class MongoDBQueueServiceProvider extends QueueServiceProvider { @@ -56,7 +52,6 @@ protected function registerFailedJobServices() protected function mongoFailedJobProvider(array $config): DatabaseFailedJobProvider { if (! isset($config['collection']) && isset($config['table'])) { - trigger_error('Since mongodb/laravel-mongodb 4.4: Using "table" option for the queue is deprecated. Use "collection" instead.', E_USER_DEPRECATED); $config['collection'] = $config['table']; } diff --git a/src/Query/Builder.php b/src/Query/Builder.php index a8717f212..ddbca69fe 100644 --- a/src/Query/Builder.php +++ b/src/Query/Builder.php @@ -595,7 +595,7 @@ public function aggregate($function = null, $columns = ['*']) if (isset($results[0])) { $result = (array) $results[0]; - return $this->aliasIdForResult($result['aggregate']); + return $result['aggregate']; } } diff --git a/src/Queue/Failed/MongoFailedJobProvider.php b/src/Queue/Failed/MongoFailedJobProvider.php deleted file mode 100644 index f130036ce..000000000 --- a/src/Queue/Failed/MongoFailedJobProvider.php +++ /dev/null @@ -1,12 +0,0 @@ -first(); - $this->assertInstanceOf(\stdClass::class, $result); + $this->assertInstanceOf(stdClass::class, $result); $this->assertInstanceOf(ObjectId::class, $result->_id); $this->assertSame('John Doe', $result->name); } diff --git a/tests/QueryBuilderTest.php b/tests/QueryBuilderTest.php index 8cb5e3116..11f0d8bbc 100644 --- a/tests/QueryBuilderTest.php +++ b/tests/QueryBuilderTest.php @@ -32,7 +32,6 @@ use function md5; use function sort; use function strlen; -use function strtotime; class QueryBuilderTest extends TestCase { diff --git a/tests/Queue/Failed/MongoFailedJobProviderTest.php b/tests/Queue/Failed/DatabaseFailedJobProviderTest.php similarity index 92% rename from tests/Queue/Failed/MongoFailedJobProviderTest.php rename to tests/Queue/Failed/DatabaseFailedJobProviderTest.php index 7996b5723..27fb1780f 100644 --- a/tests/Queue/Failed/MongoFailedJobProviderTest.php +++ b/tests/Queue/Failed/DatabaseFailedJobProviderTest.php @@ -2,11 +2,11 @@ namespace MongoDB\Laravel\Tests\Queue\Failed; +use Illuminate\Queue\Failed\DatabaseFailedJobProvider; use Illuminate\Support\Facades\Date; use Illuminate\Support\Facades\DB; use MongoDB\BSON\ObjectId; use MongoDB\BSON\UTCDateTime; -use MongoDB\Laravel\Queue\Failed\MongoFailedJobProvider; use MongoDB\Laravel\Tests\TestCase; use OutOfBoundsException; @@ -14,7 +14,10 @@ use function range; use function sprintf; -class MongoFailedJobProviderTest extends TestCase +/** + * Test the Laravel class with MongoDB's Query Builder + */ +class DatabaseFailedJobProviderTest extends TestCase { public function setUp(): void { @@ -142,8 +145,8 @@ public function testPrune(): void $this->assertEquals(3, $provider->count()); } - private function getProvider(): MongoFailedJobProvider + private function getProvider(): DatabaseFailedJobProvider { - return new MongoFailedJobProvider(DB::getFacadeRoot(), '', 'failed_jobs'); + return new DatabaseFailedJobProvider(DB::getFacadeRoot(), '', 'failed_jobs'); } } diff --git a/tests/QueueTest.php b/tests/QueueTest.php index ce6458dad..6e1229e98 100644 --- a/tests/QueueTest.php +++ b/tests/QueueTest.php @@ -10,8 +10,6 @@ use Illuminate\Support\Facades\Queue; use Illuminate\Support\Str; use Mockery; -use MongoDB\BSON\UTCDateTime; -use MongoDB\Laravel\Queue\Failed\MongoFailedJobProvider; use MongoDB\Laravel\Queue\MongoJob; use MongoDB\Laravel\Queue\MongoQueue; From 0596b0a147dc54d1b86004770440c743eb92d076 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=A9r=C3=B4me=20Tamarelle?= Date: Mon, 15 Jul 2024 12:08:03 +0200 Subject: [PATCH 09/10] Remove date conversion from results --- docs/includes/usage-examples/FindOneTest.php | 4 ++-- docs/includes/usage-examples/InsertOneTest.php | 2 +- src/Query/Builder.php | 8 ++------ tests/AuthTest.php | 3 ++- tests/Casts/DecimalTest.php | 2 +- tests/QueueTest.php | 3 ++- 6 files changed, 10 insertions(+), 12 deletions(-) diff --git a/docs/includes/usage-examples/FindOneTest.php b/docs/includes/usage-examples/FindOneTest.php index 98452a6a6..e46ba1be4 100644 --- a/docs/includes/usage-examples/FindOneTest.php +++ b/docs/includes/usage-examples/FindOneTest.php @@ -24,13 +24,13 @@ public function testFindOne(): void // begin-find-one $movie = Movie::where('directors', 'Rob Reiner') - ->orderBy('_id') + ->orderBy('id') ->first(); echo $movie->toJson(); // end-find-one $this->assertInstanceOf(Movie::class, $movie); - $this->expectOutputRegex('/^{"_id":"[a-z0-9]{24}","title":"The Shawshank Redemption","directors":\["Frank Darabont","Rob Reiner"\]}$/'); + $this->expectOutputRegex('/^{"title":"The Shawshank Redemption","directors":\["Frank Darabont","Rob Reiner"\],"id":"[a-z0-9]{24}"}$/'); } } diff --git a/docs/includes/usage-examples/InsertOneTest.php b/docs/includes/usage-examples/InsertOneTest.php index 15eadf419..7e4de48d6 100644 --- a/docs/includes/usage-examples/InsertOneTest.php +++ b/docs/includes/usage-examples/InsertOneTest.php @@ -30,6 +30,6 @@ public function testInsertOne(): void // end-insert-one $this->assertInstanceOf(Movie::class, $movie); - $this->expectOutputRegex('/^{"title":"Marriage Story","year":2019,"runtime":136,"updated_at":".{27}","created_at":".{27}","_id":"[a-z0-9]{24}"}$/'); + $this->expectOutputRegex('/^{"title":"Marriage Story","year":2019,"runtime":136,"updated_at":".{27}","created_at":".{27}","id":"[a-z0-9]{24}"}$/'); } } diff --git a/src/Query/Builder.php b/src/Query/Builder.php index ddbca69fe..e9978d211 100644 --- a/src/Query/Builder.php +++ b/src/Query/Builder.php @@ -1593,9 +1593,7 @@ private function aliasIdForResult(stdClass|array $values): stdClass|array } foreach ($values as $key => $value) { - if ($value instanceof UTCDateTime) { - $values[$key] = CarbonImmutable::createFromTimestamp($value->toDateTime()->getTimestamp(), 'UTC')->setTimezone(date_default_timezone_get()); - } elseif (is_array($value) || $value instanceof stdClass) { + if (is_array($value) || $value instanceof stdClass) { $values[$key] = $this->aliasIdForResult($value); } } @@ -1606,9 +1604,7 @@ private function aliasIdForResult(stdClass|array $values): stdClass|array } foreach (get_object_vars($values) as $key => $value) { - if ($value instanceof UTCDateTime) { - $values->{$key} = CarbonImmutable::createFromTimestamp($value->toDateTime()->getTimestamp(), 'UTC')->setTimezone(date_default_timezone_get()); - } elseif (is_array($value) || $value instanceof stdClass) { + if (is_array($value) || $value instanceof stdClass) { $values->{$key} = $this->aliasIdForResult($value); } } diff --git a/tests/AuthTest.php b/tests/AuthTest.php index 4f304767f..998fbaae5 100644 --- a/tests/AuthTest.php +++ b/tests/AuthTest.php @@ -9,6 +9,7 @@ use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Hash; +use MongoDB\BSON\UTCDateTime; use MongoDB\Laravel\Tests\Models\User; use function bcrypt; @@ -63,7 +64,7 @@ function ($actualUser, $actualToken) use ($user, &$token) { $reminder = DB::collection('password_reset_tokens')->first(); $this->assertEquals('john.doe@example.com', $reminder->email); $this->assertNotNull($reminder->token); - $this->assertInstanceOf(DateTimeInterface::class, $reminder->created_at); + $this->assertInstanceOf(UTCDateTime::class, $reminder->created_at); $credentials = [ 'email' => 'john.doe@example.com', diff --git a/tests/Casts/DecimalTest.php b/tests/Casts/DecimalTest.php index e4e5ced7f..cd6d04dd8 100644 --- a/tests/Casts/DecimalTest.php +++ b/tests/Casts/DecimalTest.php @@ -120,7 +120,7 @@ private function setBSONType($value, $id = null) return Casting::raw(function (Collection $collection) use ($id, $value) { if (! empty($id)) { return $collection->updateOne( - ['id' => $id], + ['_id' => $id], // "id" is not translated to "_id" by the raw method ['$set' => ['decimalNumber' => $value]], ); } diff --git a/tests/QueueTest.php b/tests/QueueTest.php index 6e1229e98..a14a76d0c 100644 --- a/tests/QueueTest.php +++ b/tests/QueueTest.php @@ -10,6 +10,7 @@ use Illuminate\Support\Facades\Queue; use Illuminate\Support\Str; use Mockery; +use MongoDB\BSON\UTCDateTime; use MongoDB\Laravel\Queue\MongoJob; use MongoDB\Laravel\Queue\MongoQueue; @@ -188,7 +189,7 @@ public function testFailedJobLogging() $this->assertSame('test_connection', $failedJob->connection); $this->assertSame('test_queue', $failedJob->queue); $this->assertSame('test_payload', $failedJob->payload); - $this->assertEquals(Carbon::now(), $failedJob->failed_at); + $this->assertEquals(new UTCDateTime(Carbon::now()), $failedJob->failed_at); $this->assertStringStartsWith('Exception: test_exception in ', $failedJob->exception); } } From d5922413d3cad6b08f31266a8b5da10aeb2bcbad Mon Sep 17 00:00:00 2001 From: GromNaN Date: Mon, 15 Jul 2024 10:08:41 +0000 Subject: [PATCH 10/10] apply phpcbf formatting --- src/Query/Builder.php | 2 -- tests/AuthTest.php | 1 - 2 files changed, 3 deletions(-) diff --git a/src/Query/Builder.php b/src/Query/Builder.php index e9978d211..a250d0e07 100644 --- a/src/Query/Builder.php +++ b/src/Query/Builder.php @@ -6,7 +6,6 @@ use ArgumentCountError; use BadMethodCallException; -use Carbon\CarbonImmutable; use Carbon\CarbonPeriod; use Closure; use DateTimeInterface; @@ -41,7 +40,6 @@ use function call_user_func_array; use function count; use function ctype_xdigit; -use function date_default_timezone_get; use function dd; use function dump; use function end; diff --git a/tests/AuthTest.php b/tests/AuthTest.php index 998fbaae5..531cacd25 100644 --- a/tests/AuthTest.php +++ b/tests/AuthTest.php @@ -4,7 +4,6 @@ namespace MongoDB\Laravel\Tests; -use DateTimeInterface; use Illuminate\Auth\Passwords\PasswordBroker; use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\DB;