Created
September 24, 2021 01:46
-
-
Save macbookandrew/8baf9144cc8c359728410347e6f92e95 to your computer and use it in GitHub Desktop.
MeiliSearch PHP facets
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
trait HasRefinements | |
{ | |
public static function convertFiltersForMeiliSearch(array $filters, mixed $parentKey = null) | |
{ | |
$return = []; | |
foreach ($filters as $key => $value) { | |
if (! is_null($parentKey)) { | |
$key = $parentKey; | |
} | |
if (is_array($value)) { | |
$return[] = self::convertFiltersForMeiliSearch($value, $key); | |
} else { | |
// If indexed array key, just pass it through. | |
if (is_int($key)) { | |
$return[] = $value; | |
continue; | |
} | |
if (false !== strpos($value, ' ')) { | |
$value = '"' . $value . '"'; | |
} | |
$return[] = $key . '=' . $value; | |
} | |
} | |
return $return; | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace Tests\Feature; | |
use App\Http\Livewire\HasRefinements; | |
use Tests\TestCase; | |
class HasRefinementsTraitTest extends TestCase | |
{ | |
public function test_convert_for_meilisearch() | |
{ | |
$filters = [ | |
'brand' => 'Bostitch', | |
'vendor' => 'Acme Inc', | |
'colors' => [ | |
'White', | |
'Nantucket White', | |
'Ivory', | |
], | |
'price > 7', | |
'price < 10', | |
]; | |
$this->assertEquals( | |
[ | |
'brand=Bostitch', | |
'vendor="Acme Inc"', | |
[ | |
'colors=White', | |
'colors="Nantucket White"', | |
'colors=Ivory', | |
], | |
'price > 7', | |
'price < 10', | |
], | |
TestHasRefinements::convertFiltersForMeiliSearch($filters) | |
); | |
} | |
} | |
class TestHasRefinements | |
{ | |
use HasRefinements; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment