Skip to content

Instantly share code, notes, and snippets.

@macbookandrew
Created September 24, 2021 01:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save macbookandrew/8baf9144cc8c359728410347e6f92e95 to your computer and use it in GitHub Desktop.
Save macbookandrew/8baf9144cc8c359728410347e6f92e95 to your computer and use it in GitHub Desktop.
MeiliSearch PHP facets
<?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;
}
}
<?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