Skip to content

Commit dcce3c1

Browse files
authored
Add Conditionable trait (#54)
1 parent a3bed78 commit dcce3c1

File tree

2 files changed

+24
-0
lines changed

2 files changed

+24
-0
lines changed

src/Searcher.php

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,9 +13,12 @@
1313
use Illuminate\Support\Collection;
1414
use Illuminate\Support\Facades\DB;
1515
use Illuminate\Support\Str;
16+
use Illuminate\Support\Traits\Conditionable;
1617

1718
class Searcher
1819
{
20+
use Conditionable;
21+
1922
/**
2023
* Collection of models to search through.
2124
*/

tests/SearchTest.php

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
use Illuminate\Support\Collection;
99
use ProtoneMedia\LaravelCrossEloquentSearch\OrderByRelevanceException;
1010
use ProtoneMedia\LaravelCrossEloquentSearch\Search;
11+
use ProtoneMedia\LaravelCrossEloquentSearch\Searcher;
1112

1213
class SearchTest extends TestCase
1314
{
@@ -654,4 +655,24 @@ public function it_returns_data_consistently() {
654655
$this->assertTrue($resultA->first()->is($postA));
655656
$this->assertTrue($resultB->first()->is($postA));
656657
}
658+
659+
/** @test */
660+
public function it_can_conditionally_apply_ordering()
661+
{
662+
Carbon::setTestNow(now());
663+
$postA = Post::create(['title' => 'foo']);
664+
665+
Carbon::setTestNow(now()->subDay());
666+
$postB = Post::create(['title' => 'foo2']);
667+
668+
$results = Search::add(Post::class, 'title')
669+
->when(true, fn (Searcher $searcher) => $searcher->orderByDesc())
670+
->get('foo');
671+
672+
$this->assertInstanceOf(Collection::class, $results);
673+
$this->assertCount(2, $results);
674+
675+
$this->assertTrue($results->first()->is($postA));
676+
$this->assertTrue($results->last()->is($postB));
677+
}
657678
}

0 commit comments

Comments
 (0)