Skip to content

Commit 3d030ba

Browse files
committed
Cleaning
1 parent bebdd1d commit 3d030ba

File tree

4 files changed

+46
-39
lines changed

4 files changed

+46
-39
lines changed

src/Scout/ScoutEngine.php

+14-13
Original file line numberDiff line numberDiff line change
@@ -68,7 +68,7 @@ final class ScoutEngine extends Engine
6868
];
6969

7070
public function __construct(
71-
private Database $mongodb,
71+
private Database $database,
7272
private bool $softDelete,
7373
private string $prefix,
7474
) {
@@ -203,6 +203,7 @@ protected function performSearch(Builder $builder, ?int $offset = null): array
203203
],
204204
],
205205
],
206+
'minimumShouldMatch' => 1,
206207
];
207208

208209
// "filter" specifies conditions on exact values to match
@@ -238,7 +239,7 @@ protected function performSearch(Builder $builder, ?int $offset = null): array
238239
],
239240
[
240241
'$addFields' => [
241-
'search_meta' => '$$SEARCH_META',
242+
'__count' => '$$SEARCH_META.count.lowerBound',
242243
],
243244
],
244245
];
@@ -298,7 +299,7 @@ public function map(Builder $builder, $results, $model): Collection
298299
$result = $results[$objectIdPositions[$model->getScoutKey()]] ?? [];
299300

300301
foreach ($result as $key => $value) {
301-
if (substr($key, 0, 1) === '_') {
302+
if ($key[0] === '_') {
302303
$model->withScoutMetadata($key, $value);
303304
}
304305
}
@@ -321,7 +322,7 @@ public function getTotalCount($results): int
321322
return 0;
322323
}
323324

324-
return $results[0]->search_meta['count']['lowerBound'];
325+
return $results[0]->__count;
325326
}
326327

327328
/**
@@ -393,9 +394,9 @@ public function createIndex($name, array $options = []): void
393394
assert(is_string($name), new TypeError(sprintf('Argument #1 ($name) must be of type string, %s given', get_debug_type($name))));
394395

395396
// Ensure the collection exists before creating the search index
396-
$this->mongodb->createCollection($name);
397+
$this->database->createCollection($name);
397398

398-
$collection = $this->mongodb->selectCollection($name);
399+
$collection = $this->database->selectCollection($name);
399400
$collection->createSearchIndex(
400401
self::DEFAULT_DEFINITION,
401402
['name' => self::INDEX_NAME],
@@ -420,22 +421,22 @@ public function deleteIndex($name): void
420421
{
421422
assert(is_string($name), new TypeError(sprintf('Argument #1 ($name) must be of type string, %s given', get_debug_type($name))));
422423

423-
$this->mongodb->selectCollection($name)->drop();
424+
$this->database->selectCollection($name)->drop();
424425
}
425426

426427
/**
427428
* Delete all "search indexes", i.e. all MongoDB collections.
428429
*/
429430
public function deleteAllIndexes()
430431
{
431-
$collectionNames = $this->mongodb->listCollectionNames([
432+
$collectionNames = $this->database->listCollectionNames([
432433
'filter' => [
433434
'name' => new Regex('^' . preg_quote($this->prefix)),
434435
],
435436
]);
436437

437438
foreach ($collectionNames as $collectionName) {
438-
$this->mongodb->selectCollection($collectionName)->drop();
439+
$this->database->selectCollection($collectionName)->drop();
439440
}
440441
}
441442

@@ -448,7 +449,7 @@ private function getSearchableCollection(Model|EloquentCollection $model): Mongo
448449

449450
assert(in_array(Searchable::class, class_uses_recursive($model)), sprintf('Model "%s" must use "%s" trait', $model::class, Searchable::class));
450451

451-
return $this->mongodb->selectCollection($model->searchableAs());
452+
return $this->database->selectCollection($model->searchableAs());
452453
}
453454

454455
/** Get the MongoDB collection used to index the provided model */
@@ -463,13 +464,13 @@ private function getIndexableCollection(Model|EloquentCollection $model): MongoD
463464

464465
if (
465466
$model->getConnection() instanceof Connection
466-
&& $model->getConnection()->getDatabaseName() === $this->mongodb->getDatabaseName()
467+
&& $model->getConnection()->getDatabaseName() === $this->database->getDatabaseName()
467468
&& $model->getTable() === $model->indexableAs()
468469
) {
469-
throw new LogicException(sprintf('The MongoDB Scout collection "%s.%s" must use a different collection from the collection name of the model "%s". Set the "scout.prefix" configuration or use a distinct MongoDB database', $this->mongodb->getDatabaseName(), $model->indexableAs(), $model::class));
470+
throw new LogicException(sprintf('The MongoDB Scout collection "%s.%s" must use a different collection from the collection name of the model "%s". Set the "scout.prefix" configuration or use a distinct MongoDB database', $this->database->getDatabaseName(), $model->indexableAs(), $model::class));
470471
}
471472

472-
return $this->mongodb->selectCollection($model->indexableAs());
473+
return $this->database->selectCollection($model->indexableAs());
473474
}
474475

475476
private static function serialize(mixed $value): mixed

tests/ModelTest.php

+2-1
Original file line numberDiff line numberDiff line change
@@ -406,8 +406,9 @@ public function testSoftDelete(): void
406406
$this->assertEquals(2, Soft::count());
407407
}
408408

409+
/** @param class-string<Model> $model */
409410
#[DataProvider('provideId')]
410-
public function testPrimaryKey(string $model, $id, $expected, bool $expectedFound): void
411+
public function testPrimaryKey(string $model, mixed $id, mixed $expected, bool $expectedFound): void
411412
{
412413
$model::truncate();
413414
$expectedType = get_debug_type($expected);

tests/Scout/ScoutEngineTest.php

+22-4
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
use Illuminate\Support\Collection as IlluminateCollection;
1010
use Laravel\Scout\Builder;
1111
use Laravel\Scout\Jobs\RemoveFromSearch;
12+
use LogicException;
1213
use Mockery as m;
1314
use MongoDB\BSON\Document;
1415
use MongoDB\BSON\Regex;
@@ -17,13 +18,16 @@
1718
use MongoDB\Database;
1819
use MongoDB\Driver\CursorInterface;
1920
use MongoDB\Laravel\Scout\ScoutEngine;
21+
use MongoDB\Laravel\Tests\Models\SearchableInSameNamespace;
2022
use MongoDB\Laravel\Tests\Models\SearchableModel;
2123
use MongoDB\Laravel\Tests\TestCase;
2224
use MongoDB\Model\BSONDocument;
2325
use PHPUnit\Framework\Attributes\DataProvider;
2426

2527
use function array_replace_recursive;
28+
use function env;
2629
use function serialize;
30+
use function sprintf;
2731
use function unserialize;
2832

2933
/** Unit tests that do not require an Atlas Search cluster */
@@ -35,7 +39,7 @@ class ScoutEngineTest extends TestCase
3539
#[DataProvider('provideSearchPipelines')]
3640
public function testSearch(Closure $builder, array $expectedPipeline): void
3741
{
38-
$data = [['_id' => 'key_1'], ['_id' => 'key_2']];
42+
$data = [['_id' => 'key_1', '__count' => 15], ['_id' => 'key_2', '__count' => 15]];
3943
$database = m::mock(Database::class);
4044
$collection = m::mock(Collection::class);
4145
$database->shouldReceive('selectCollection')
@@ -83,6 +87,7 @@ public function provideSearchPipelines(): iterable
8387
],
8488
],
8589
],
90+
'minimumShouldMatch' => 1,
8691
],
8792
'count' => [
8893
'type' => 'lowerBound',
@@ -91,7 +96,7 @@ public function provideSearchPipelines(): iterable
9196
],
9297
[
9398
'$addFields' => [
94-
'search_meta' => '$$SEARCH_META',
99+
'__count' => '$$SEARCH_META.count.lowerBound',
95100
],
96101
],
97102
];
@@ -361,6 +366,7 @@ public function testPaginate()
361366
],
362367
],
363368
],
369+
'minimumShouldMatch' => 1,
364370
],
365371
'count' => [
366372
'type' => 'lowerBound',
@@ -372,7 +378,7 @@ public function testPaginate()
372378
],
373379
[
374380
'$addFields' => [
375-
'search_meta' => '$$SEARCH_META',
381+
'__count' => '$$SEARCH_META.count.lowerBound',
376382
],
377383
],
378384
[
@@ -391,7 +397,7 @@ public function testPaginate()
391397
$cursor->shouldReceive('toArray')
392398
->once()
393399
->with()
394-
->andReturn([['_id' => 'key_1'], ['_id' => 'key_2']]);
400+
->andReturn([['_id' => 'key_1', '__count' => 17], ['_id' => 'key_2', '__count' => 17]]);
395401

396402
$engine = new ScoutEngine($database, softDelete: false, prefix: '');
397403
$builder = new Builder(new SearchableModel(), 'mustang');
@@ -564,4 +570,16 @@ public function testDeleteAll(): void
564570
$engine = new ScoutEngine($database, softDelete: false, prefix: 'scout-prefix-');
565571
$engine->deleteAllIndexes();
566572
}
573+
574+
public function testItCannotIndexInTheSameNamespace()
575+
{
576+
self::expectException(LogicException::class);
577+
self::expectExceptionMessage(sprintf(
578+
'The MongoDB Scout collection "%s.searchable_in_same_namespaces" must use a different collection from the collection name of the model "%s". Set the "scout.prefix" configuration or use a distinct MongoDB database',
579+
env('MONGODB_DATABASE', 'unittest'),
580+
SearchableInSameNamespace::class,
581+
),);
582+
583+
SearchableInSameNamespace::create(['name' => 'test']);
584+
}
567585
}

tests/Scout/ScoutIntegrationTest.php

+8-21
Original file line numberDiff line numberDiff line change
@@ -5,20 +5,16 @@
55
use Illuminate\Database\Eloquent\Factories\Sequence;
66
use Illuminate\Support\Facades\DB;
77
use Illuminate\Support\LazyCollection;
8-
use LogicException;
98
use MongoDB\Driver\Exception\ServerException;
10-
use MongoDB\Laravel\Tests\Models\SearchableInSameNamespace;
119
use MongoDB\Laravel\Tests\Models\SqlUser;
1210
use MongoDB\Laravel\Tests\TestCase;
1311
use Orchestra\Testbench\Factories\UserFactory;
1412
use PHPUnit\Framework\Attributes\Depends;
1513

1614
use function count;
17-
use function env;
1815
use function in_array;
1916
use function Orchestra\Testbench\artisan;
2017
use function range;
21-
use function sprintf;
2218
use function usleep;
2319

2420
class ScoutIntegrationTest extends TestCase
@@ -40,7 +36,7 @@ public function testItCanCreateTheCollection()
4036
} catch (ServerException $exception) {
4137
if (
4238
in_array($exception->getCode(), [
43-
40324, // Old version: Unrecognized pipeline stage name: '$listSearchIndexes'
39+
40324, // Prior to MongoDB 6: Unrecognized pipeline stage name: '$listSearchIndexes'
4440
31082, // Community Server: Using Atlas Search Database Commands and the $listSearchIndexes aggregation stage requires additional configuration.
4541
115, // Enterprise Server: PlanExecutor error during aggregation :: caused by :: Search index commands are only supported with Atlas.
4642
])
@@ -228,29 +224,20 @@ public function testItCanUsePaginatedSearchWithQueryCallback()
228224
return $query->whereNotNull('email_verified_at');
229225
};
230226

231-
$page1 = SqlUser::search('lar')->take(10)->query($queryCallback)->paginate(3, 'page', 1);
232-
$page2 = SqlUser::search('lar')->take(10)->query($queryCallback)->paginate(3, 'page', 2);
227+
$page1 = SqlUser::search('lar')->take(10)->query($queryCallback)->paginate(5, 'page', 1);
228+
$page2 = SqlUser::search('lar')->take(10)->query($queryCallback)->paginate(5, 'page', 2);
233229

234230
self::assertSame([
235231
42 => 'Dax Larkin',
232+
44 => 'Amos Larson Sr.',
233+
43 => 'Dana Larson Sr.',
236234
], $page1->pluck('name', 'id')->all());
237235

238236
self::assertSame([
239-
44 => 'Amos Larson Sr.',
240-
43 => 'Dana Larson Sr.',
241237
41 => 'Gudrun Larkin',
238+
40 => 'Otis Larson MD',
239+
12 => 'Reta Larkin',
240+
1 => 'Laravel Framework',
242241
], $page2->pluck('name', 'id')->all());
243242
}
244-
245-
public function testItCannotIndexInTheSameNamespace()
246-
{
247-
self::expectException(LogicException::class);
248-
self::expectExceptionMessage(sprintf(
249-
'The MongoDB Scout collection "%s.searchable_in_same_namespaces" must use a different collection from the collection name of the model "%s". Set the "scout.prefix" configuration or use a distinct MongoDB database',
250-
env('MONGODB_DATABASE', 'unittest'),
251-
SearchableInSameNamespace::class,
252-
),);
253-
254-
SearchableInSameNamespace::create(['name' => 'test']);
255-
}
256243
}

0 commit comments

Comments
 (0)