-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSearchControllerTest.php
More file actions
832 lines (720 loc) · 29.5 KB
/
Copy pathSearchControllerTest.php
File metadata and controls
832 lines (720 loc) · 29.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
<?php
declare(strict_types=1);
use Capell\Core\Models\Language;
use Capell\Core\Models\Layout;
use Capell\Core\Models\Page;
use Capell\Core\Models\Site;
use Capell\Core\Models\Theme;
use Capell\Frontend\Contracts\FrontendContextReader;
use Capell\Frontend\Support\State\FrontendState;
use Capell\Search\Actions\BuildSearchPageViewDataAction;
use Capell\Search\Actions\CreateSearchVisitorIdentityAction;
use Capell\Search\Actions\GenerateSearchClickTokenAction;
use Capell\Search\Actions\HashSearchRetentionValueAction;
use Capell\Search\Contracts\Search;
use Capell\Search\Data\SearchFilterData;
use Capell\Search\Data\SearchRequestData;
use Capell\Search\Data\SearchResultData;
use Capell\Search\Http\Controllers\SearchController;
use Capell\Search\Models\SearchLog;
use Capell\Search\Providers\SearchServiceProvider;
use Capell\Search\Support\SearchableSourceRegistry;
use Illuminate\Cache\RateLimiting\Limit;
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Pagination\LengthAwarePaginator as Paginator;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\RateLimiter;
use Illuminate\Support\Facades\Route;
use Illuminate\Support\Facades\Schema;
beforeEach(function (): void {
app()->register(SearchServiceProvider::class);
config()->set('capell-search.results_per_page', 5);
config()->set('capell-search.minimum_query_length', 2);
});
afterEach(function (): void {
Schema::dropIfExists('search_logs');
});
test('autocomplete returns no results for blank or too-short queries', function (string $query): void {
app()->instance(Search::class, new class implements Search
{
public function search(
string $query,
int $perPage = 10,
int $page = 1,
?int $siteId = null,
?int $languageId = null,
?SearchFilterData $filters = null,
): LengthAwarePaginator {
throw new RuntimeException('Search should not run for blank or too-short autocomplete queries.');
}
public function highlight(string $text, string $query): string
{
return str_replace('Search', '<mark>Search</mark>', e($text));
}
});
$request = Request::create('/search/autocomplete', Symfony\Component\HttpFoundation\Request::METHOD_GET, ['q' => $query]);
$response = (new SearchController)->autocomplete($request);
expect($response->getData(true))->toMatchArray([
'query' => $query,
'minimumLength' => 2,
'results' => [],
'allResultsUrl' => route('capell-frontend.search', ['q' => $query], false),
]);
})->with(['', 'c']);
test('autocomplete returns limited public-safe results without writing search logs', function (): void {
config()->set('capell-search.autocomplete.limit', 1);
config()->set('capell-search.promoted_results', [
[
'query' => 'capell',
'title' => 'Promoted Capell result',
'url' => '/promoted-capell',
'excerpt' => 'This should not be injected into autocomplete.',
'type' => 'page',
],
]);
config()->set('capell-search.type_labels', [
'marketing_content' => 'Marketing',
]);
$recordedSearch = new stdClass;
$recordedSearch->query = null;
$recordedSearch->perPage = null;
$recordedSearch->page = null;
app()->instance(Search::class, new readonly class($recordedSearch) implements Search
{
public function __construct(private stdClass $recordedSearch) {}
public function search(
string $query,
int $perPage = 10,
int $page = 1,
?int $siteId = null,
?int $languageId = null,
?SearchFilterData $filters = null,
): LengthAwarePaginator {
$this->recordedSearch->query = $query;
$this->recordedSearch->perPage = $perPage;
$this->recordedSearch->page = $page;
return new Paginator(new Collection([
new SearchResultData(
title: 'Capell CMS',
url: '/capell-cms',
excerpt: 'Capell CMS result',
type: 'marketing_content',
score: 4.0,
),
new SearchResultData(
title: 'Hidden extra',
url: '/hidden-extra',
excerpt: 'Should be limited away',
type: 'marketing_content',
score: 1.0,
),
]), 2, $perPage, $page);
}
public function highlight(string $text, string $query): string
{
return str_replace('Search', '<mark>Search</mark>', e($text));
}
});
$request = Request::create('/search/autocomplete', Symfony\Component\HttpFoundation\Request::METHOD_GET, ['q' => 'Capell']);
$response = (new SearchController)->autocomplete($request);
$payload = searchControllerJsonPayload($response);
$results = searchControllerPayloadResults($payload);
expect($recordedSearch->query)->toBe('capell')
->and($recordedSearch->perPage)->toBe(1)
->and($recordedSearch->page)->toBe(1)
->and($payload)->toHaveKeys(['query', 'minimumLength', 'results', 'allResultsUrl'])
->and($results)->toHaveCount(1)
->and($results[0])->toBe([
'title' => 'Capell CMS',
'url' => '/capell-cms',
'excerpt' => 'Capell CMS result',
'type' => 'marketing_content',
'typeLabel' => 'Marketing',
'score' => 4,
])
->and($results[0])->not->toHaveKeys(['id', 'model', 'modelClass', 'adminUrl', 'signedUrl'])
->and(SearchLog::query()->count())->toBe(0);
});
test('autocomplete returns corrected query metadata and popular query suggestions', function (): void {
config()->set('capell-search.autocomplete.limit', 5);
config()->set('capell-search.typo_corrections', [
'capel' => 'capell',
]);
Schema::dropIfExists('search_logs');
Schema::create('search_logs', function (Blueprint $table): void {
$table->id();
$table->foreignId('site_id')->nullable()->index();
$table->foreignId('language_id')->nullable()->index();
$table->string('query');
$table->string('normalized_query')->index();
$table->string('normalized_query_hash', 64)->nullable()->index();
$table->unsignedInteger('results_count')->default(0);
$table->string('clicked_result_url')->nullable();
$table->string('clicked_result_hash', 64)->nullable()->index();
$table->string('ip_hash', 64)->nullable();
$table->string('user_agent_hash', 64)->nullable();
$table->timestamp('searched_at')->index();
$table->timestamps();
});
SearchLog::query()->insert([
[
'query' => 'Capel migration',
'normalized_query' => 'capel migration',
'results_count' => 2,
'searched_at' => now(),
'created_at' => now(),
'updated_at' => now(),
],
[
'query' => 'Capel marketplace',
'normalized_query' => 'capel marketplace',
'results_count' => 3,
'searched_at' => now(),
'created_at' => now(),
'updated_at' => now(),
],
]);
app()->instance(Search::class, new class implements Search
{
public function search(
string $query,
int $perPage = 10,
int $page = 1,
?int $siteId = null,
?int $languageId = null,
?SearchFilterData $filters = null,
): LengthAwarePaginator {
return new Paginator(new Collection, 0, $perPage, $page);
}
public function highlight(string $text, string $query): string
{
return $text;
}
});
$request = Request::create('/search/autocomplete', Symfony\Component\HttpFoundation\Request::METHOD_GET, ['q' => 'capel']);
$payload = searchControllerJsonPayload((new SearchController)->autocomplete($request));
$metadata = searchControllerPayloadArray($payload, 'metadata');
$suggestions = searchControllerPayloadSuggestions($payload);
expect($metadata['corrected'] ?? null)->toBe('capell')
->and($suggestions)->toHaveCount(2)
->and($suggestions[0]['query'] ?? null)->toBe('capel marketplace')
->and($suggestions[0]['url'] ?? null)->toBe(route('capell-frontend.search', ['q' => 'capel marketplace'], false));
});
test('autocomplete route is lightly throttled', function (): void {
$route = Route::getRoutes()->getByName('capell-frontend.search.autocomplete');
expect($route?->gatherMiddleware())->toContain('throttle:capell-search-autocomplete');
});
test('full search route is throttled', function (): void {
$route = Route::getRoutes()->getByName('capell-frontend.search');
expect($route?->gatherMiddleware())
->toContain('throttle:capell-search-requests')
->not->toContain('frontend.resolve');
});
test('click tracking route is csrf exempt for cached frontend beacons', function (): void {
$route = Route::getRoutes()->getByName('capell-frontend.search.click');
expect($route?->gatherMiddleware())->toContain('throttle:capell-search-clicks')
->and($route?->excludedMiddleware())->toContain(VerifyCsrfToken::class);
});
test('header click beacon does not require a csrf token', function (): void {
$html = view('capell-search::components.header.search-dialog')->render();
$script = file_get_contents(__DIR__ . '/../../../resources/dist/search-modal.js');
throw_unless(is_string($script), RuntimeException::class, 'Expected search modal script to be readable.');
expect($html)
->toContain('vendor/capell-search/search-modal.js')
->not()->toContain('csrf-token')
->not()->toContain('X-CSRF-TOKEN')
->and($script)
->toContain("mode: 'no-cors'")
->not()->toContain('csrf-token')
->not()->toContain('X-CSRF-TOKEN');
});
test('result click beacon does not require a csrf token', function (): void {
$html = view('capell-search::components.results', [
'clickTrackingTokens' => [],
'query' => '',
'results' => new Paginator(new Collection, 0, 5, 1),
])->render();
expect($html)
->toContain('window.capellSearchClickBeaconInitialized')
->toContain("mode: 'no-cors'")
->toContain("body.set('token',")
->not()->toContain('csrf-token')
->not()->toContain('X-CSRF-TOKEN');
});
test('click tracking endpoint records result clicks by token', function (): void {
RateLimiter::for('capell-search-clicks', static fn (): Limit => Limit::perMinute(120));
Schema::dropIfExists('search_logs');
Schema::create('search_logs', function (Blueprint $table): void {
$table->id();
$table->foreignId('site_id')->nullable()->index();
$table->foreignId('language_id')->nullable()->index();
$table->string('query');
$table->string('normalized_query')->index();
$table->string('normalized_query_hash', 64)->nullable()->index();
$table->unsignedInteger('results_count')->default(0);
$table->string('clicked_result_url')->nullable();
$table->string('clicked_result_hash', 64)->nullable()->index();
$table->string('ip_hash', 64)->nullable();
$table->string('user_agent_hash', 64)->nullable();
$table->timestamp('searched_at')->index();
$table->timestamps();
});
$searchData = new SearchRequestData(query: 'Laravel Search');
$log = SearchLog::query()->create([
'query' => 'Laravel Search',
'normalized_query' => HashSearchRetentionValueAction::run('laravel search'),
'normalized_query_hash' => HashSearchRetentionValueAction::run('laravel search'),
'results_count' => 1,
'searched_at' => now(),
]);
$token = GenerateSearchClickTokenAction::run($searchData, '/laravel-search');
$this
->withoutMiddleware()
->post(route('capell-frontend.search.click'), [
'query' => 'Laravel Search',
'url' => '/laravel-search',
'token' => $token,
])
->assertNoContent();
expect($log->refresh()->clicked_result_url)->toBe('/laravel-search');
});
test('click tracking endpoint enforces its configured rate limiter', function (): void {
RateLimiter::for('capell-search-clicks', static fn (): Limit => Limit::perMinute(1)->by('search-click-test'));
Schema::dropIfExists('search_logs');
Schema::create('search_logs', function (Blueprint $table): void {
$table->id();
$table->foreignId('site_id')->nullable()->index();
$table->foreignId('language_id')->nullable()->index();
$table->string('query');
$table->string('normalized_query')->index();
$table->string('normalized_query_hash', 64)->nullable()->index();
$table->unsignedInteger('results_count')->default(0);
$table->string('clicked_result_url')->nullable();
$table->string('clicked_result_hash', 64)->nullable()->index();
$table->string('ip_hash', 64)->nullable();
$table->string('user_agent_hash', 64)->nullable();
$table->timestamp('searched_at')->index();
$table->timestamps();
});
Route::post('/_search-click-rate-limit-test', [SearchController::class, 'click'])
->middleware('throttle:capell-search-clicks')
->withoutMiddleware([VerifyCsrfToken::class]);
$payload = [
'query' => 'Laravel Search',
'url' => '/laravel-search',
];
$this->post('/_search-click-rate-limit-test', $payload)->assertNoContent();
$this->post('/_search-click-rate-limit-test', $payload)->assertTooManyRequests();
});
test('controller uses configured page view when it exists', function (): void {
config()->set('capell-search.page_view', 'capell-search::components.form');
app()->instance(Search::class, new class implements Search
{
public function search(
string $query,
int $perPage = 10,
int $page = 1,
?int $siteId = null,
?int $languageId = null,
?SearchFilterData $filters = null,
): LengthAwarePaginator {
return new Paginator(new Collection, 0, $perPage, $page);
}
public function highlight(string $text, string $query): string
{
return $text;
}
});
$request = Request::create('/search', Symfony\Component\HttpFoundation\Request::METHOD_GET, ['q' => 'Capell']);
$view = (new SearchController)($request);
$html = $view->render();
expect($view->name())->toBe('capell-search::components.form')
->and($view->getData()['query'])->toBe('Capell')
->and($html)->toContain('Search this site')
->and($html)->toContain('placeholder="Search pages, extensions, resources, and media"')
->and($html)->toContain('placeholder:text-outline-variant')
->and($html)->toContain('text-primary-on');
});
test('builds reusable search page view data through an action boundary', function (): void {
config()->set('capell-search.filters.enabled', false);
app()->instance(Search::class, new class implements Search
{
public function search(
string $query,
int $perPage = 10,
int $page = 1,
?int $siteId = null,
?int $languageId = null,
?SearchFilterData $filters = null,
): LengthAwarePaginator {
return new Paginator(new Collection([
new SearchResultData(
title: 'Laravel Search',
url: '/laravel-search',
excerpt: 'Search result content',
),
]), 1, $perPage, $page);
}
public function highlight(string $text, string $query): string
{
return str_replace('Search', '<mark>Search</mark>', e($text));
}
});
$request = Request::create('/search', Symfony\Component\HttpFoundation\Request::METHOD_GET, ['q' => 'Laravel Search']);
$viewData = BuildSearchPageViewDataAction::run($request);
$payload = $viewData->toViewData();
expect($viewData->query)->toBe('Laravel Search')
->and($viewData->results->total())->toBe(1)
->and($viewData->highlightedResults->first())->toBe([
'title' => 'Laravel <mark>Search</mark>',
'excerpt' => '<mark>Search</mark> result content',
])
->and($viewData->clickTrackingTokens)->toBeArray()
->and($payload)->toHaveKeys([
'highlightedResults',
'facetGroups',
'clickTrackingTokens',
'query',
'results',
]);
});
test('controller returns the search page view with an empty paginator for a blank query', function (): void {
app()->instance(Search::class, new class implements Search
{
public function search(
string $query,
int $perPage = 10,
int $page = 1,
?int $siteId = null,
?int $languageId = null,
?SearchFilterData $filters = null,
): LengthAwarePaginator {
throw new RuntimeException('Search should not run for a blank query.');
}
public function highlight(string $text, string $query): string
{
return $text;
}
});
$request = Request::create('/search', Symfony\Component\HttpFoundation\Request::METHOD_GET, ['q' => ' ']);
$view = (new SearchController)($request);
expect($view->name())->toBe('capell-search::pages.search');
expect($view->getData()['query'])->toBe(' ');
expect($view->getData()['results'])->toBeInstanceOf(LengthAwarePaginator::class);
expect($view->getData()['results']->total())->toBe(0);
});
test('controller does not hide frontend shell failures behind a broad throwable catch', function (): void {
$source = file_get_contents(__DIR__ . '/../../../src/Http/Controllers/SearchController.php');
throw_unless(is_string($source), RuntimeException::class, 'Expected SearchController source to be readable.');
expect($source)
->not()->toContain('use Throwable;')
->not()->toContain('catch (Throwable)');
});
test('controller wraps the search page in the frontend shell when context is available', function (): void {
app()->instance(Search::class, new class implements Search
{
public function search(
string $query,
int $perPage = 10,
int $page = 1,
?int $siteId = null,
?int $languageId = null,
?SearchFilterData $filters = null,
): LengthAwarePaginator {
throw new RuntimeException('Search should not run for a blank query.');
}
public function highlight(string $text, string $query): string
{
return $text;
}
});
$site = new Site;
$site->setRawAttributes(['id' => 1, 'name' => 'Capell']);
$language = new Language;
$language->setRawAttributes(['id' => 1, 'name' => 'English', 'code' => 'en']);
$page = new Page;
$page->setRawAttributes(['id' => 1, 'name' => 'Search']);
$layout = new Layout;
$layout->setRawAttributes([
'id' => 1,
'name' => 'Default',
'meta' => json_encode(['container' => 'xl'], JSON_THROW_ON_ERROR),
]);
$theme = new Theme;
$theme->setRawAttributes([
'id' => 1,
'name' => 'Minimal',
'meta' => json_encode(['header' => false, 'footer' => false], JSON_THROW_ON_ERROR),
]);
app()->instance(
FrontendContextReader::class,
(new FrontendState)
->withSite($site)
->withLanguage($language)
->withPage($page)
->withLayout($layout)
->withTheme($theme),
);
$request = Request::create('/search', Symfony\Component\HttpFoundation\Request::METHOD_GET, ['q' => '']);
$view = (new SearchController)($request);
expect($view->name())->toBe('capell::app')
->and($view->getData()['site'])->toBe($site)
->and($view->getData()['language'])->toBe($language)
->and($view->getData()['pageRecord'])->toBe($page)
->and($view->getData()['layout'])->toBe($layout)
->and($view->getData()['theme'])->toBe($theme)
->and((string) $view->getData()['slot'])->toContain('search-layout')
->and((string) $view->getData()['slot'])->toContain('Search this site');
});
test('controller passes normalized valid searches to the site search service', function (): void {
$recordedSearch = new stdClass;
$recordedSearch->queries = [];
app()->instance(Search::class, new readonly class($recordedSearch) implements Search
{
public function __construct(private stdClass $recordedSearch) {}
public function search(
string $query,
int $perPage = 10,
int $page = 1,
?int $siteId = null,
?int $languageId = null,
?SearchFilterData $filters = null,
): LengthAwarePaginator {
$this->recordedSearch->queries[] = $query;
$results = new Collection([
new SearchResultData(
title: 'Laravel Search',
url: '/laravel-search',
excerpt: 'Search result content',
),
]);
return new Paginator($results, 1, $perPage, $page);
}
public function highlight(string $text, string $query): string
{
return str_replace('Search', '<mark>Search</mark>', e($text));
}
});
$request = Request::create('/search', Symfony\Component\HttpFoundation\Request::METHOD_GET, ['q' => ' Laravel Search ', 'page' => '2']);
$view = (new SearchController)($request);
expect($recordedSearch->queries)->toBe(['laravel search']);
expect($view->getData()['results']->total())->toBe(1);
expect($view->getData()['results']->currentPage())->toBe(2);
expect($view->getData()['results']->perPage())->toBe(5);
expect($view->getData()['results']->url(3))->toBe('http://localhost/search?page=3');
expect($view->getData()['highlightedResults']->first())->toBe([
'title' => 'Laravel <mark>Search</mark>',
'excerpt' => '<mark>Search</mark> result content',
]);
expect($view->render())->toContain('Laravel <mark>Search</mark>');
});
test('controller defers search log writes until after the response', function (): void {
app()->instance(Search::class, new class implements Search
{
public function search(
string $query,
int $perPage = 10,
int $page = 1,
?int $siteId = null,
?int $languageId = null,
?SearchFilterData $filters = null,
): LengthAwarePaginator {
return new Paginator(new Collection([
new SearchResultData(
title: 'Laravel Search',
url: '/laravel-search',
excerpt: 'Search result content',
),
]), 1, $perPage, $page);
}
public function highlight(string $text, string $query): string
{
return $text;
}
});
$request = Request::create('/search', Symfony\Component\HttpFoundation\Request::METHOD_GET, ['q' => 'Laravel Search'], server: [
'REMOTE_ADDR' => '203.0.113.10',
'HTTP_USER_AGENT' => 'Capell Test Browser',
]);
$site = Site::factory()->createOne();
$request->attributes->set('site', $site);
$siteKey = $site->getKey();
throw_unless(is_int($siteKey), RuntimeException::class, 'Expected an integer site key.');
$expectedVisitorIdentity = CreateSearchVisitorIdentityAction::run($request, $siteKey);
(new SearchController)($request);
expect(SearchLog::query()->count())->toBe(0);
app()->terminate();
$log = SearchLog::query()->first();
expect(SearchLog::query()->count())->toBe(1)
->and($log)->toBeInstanceOf(SearchLog::class);
throw_unless($log instanceof SearchLog, RuntimeException::class, 'Expected deferred search log.');
expect($log->query)->toBe('laravel search')
->and($log->results_count)->toBe(1)
->and($log->site_id)->toBe($site->getKey())
->and($log->getAttribute('ip_hash'))->toBe($expectedVisitorIdentity->ipHash)
->and($log->getAttribute('user_agent_hash'))->toBe($expectedVisitorIdentity->userAgentHash);
});
test('controller renders public filter facets with live counts', function (): void {
config()->set('capell-search.searchables', [
'pages' => [
'label' => 'Pages',
'model' => Model::class,
'type' => 'page',
'enabled' => true,
],
'articles' => [
'label' => 'Articles',
'model' => Model::class,
'type' => 'article',
'enabled' => true,
],
]);
app()->forgetInstance(SearchableSourceRegistry::class);
app()->instance(Search::class, new class implements Search
{
public function search(
string $query,
int $perPage = 10,
int $page = 1,
?int $siteId = null,
?int $languageId = null,
?SearchFilterData $filters = null,
): LengthAwarePaginator {
$total = match (true) {
$filters?->types === ['page'] => 2,
$filters?->types === ['article'] => 1,
$filters?->sourceKeys === ['pages'] => 2,
$filters?->sourceKeys === ['articles'] => 1,
default => 3,
};
return new Paginator(new Collection([
new SearchResultData(
title: 'Laravel Search',
url: '/laravel-search',
excerpt: 'Search result content',
type: 'page',
),
]), $total, $perPage, $page);
}
public function highlight(string $text, string $query): string
{
return e($text);
}
});
$request = Request::create('/search', Symfony\Component\HttpFoundation\Request::METHOD_GET, [
'q' => 'Laravel',
'type' => ['page'],
]);
$view = (new SearchController)($request);
$html = $view->render();
expect($view->getData()['facetGroups'])->toHaveCount(2)
->and($html)->toContain('Search filters')
->and($html)->toContain('Type')
->and($html)->toContain('Page')
->and($html)->toContain('Article')
->and($html)->toContain('Source')
->and($html)->toContain('Pages')
->and($html)->toContain('Articles')
->and($html)->toContain('aria-current="true"')
->and($html)->not()->toContain('capell-search');
});
test('public search markup does not expose package identifiers', function (): void {
app()->instance(Search::class, new class implements Search
{
public function search(
string $query,
int $perPage = 10,
int $page = 1,
?int $siteId = null,
?int $languageId = null,
?SearchFilterData $filters = null,
): LengthAwarePaginator {
return new Paginator(new Collection([
new SearchResultData(
title: 'Laravel Search',
url: '/laravel-search',
excerpt: 'Search result content',
),
]), 1, $perPage, $page);
}
public function highlight(string $text, string $query): string
{
return e($text);
}
});
$request = Request::create('/search', Symfony\Component\HttpFoundation\Request::METHOD_GET, ['q' => 'Laravel']);
$html = (new SearchController)($request)->render();
expect($html)
->not()->toContain('capell-search')
->not()->toContain('capell-header-search')
->not()->toContain('package')
->not()->toContain('editor');
});
/**
* @return array<string, mixed>
*/
function searchControllerJsonPayload(JsonResponse $response): array
{
$payload = $response->getData(true);
return is_array($payload) ? searchControllerStringKeyedArray($payload) : [];
}
/**
* @param array<string, mixed> $payload
* @return array<string, mixed>
*/
function searchControllerPayloadArray(array $payload, string $key): array
{
$value = $payload[$key] ?? null;
return is_array($value) ? searchControllerStringKeyedArray($value) : [];
}
/**
* @param array<string, mixed> $payload
* @return list<array<string, mixed>>
*/
function searchControllerPayloadResults(array $payload): array
{
return searchControllerListOfStringKeyedArrays($payload['results'] ?? []);
}
/**
* @param array<string, mixed> $payload
* @return list<array<string, mixed>>
*/
function searchControllerPayloadSuggestions(array $payload): array
{
return searchControllerListOfStringKeyedArrays($payload['querySuggestions'] ?? []);
}
/**
* @return list<array<string, mixed>>
*/
function searchControllerListOfStringKeyedArrays(mixed $items): array
{
if (! is_array($items)) {
return [];
}
$results = [];
foreach ($items as $item) {
if (is_array($item)) {
$results[] = searchControllerStringKeyedArray($item);
}
}
return $results;
}
/**
* @param array<mixed> $values
* @return array<string, mixed>
*/
function searchControllerStringKeyedArray(array $values): array
{
$result = [];
foreach ($values as $key => $value) {
if (is_string($key)) {
$result[$key] = $value;
}
}
return $result;
}