Skip to content

Commit

Permalink
Allow transforming of search index values (#2462)
Browse files Browse the repository at this point in the history
  • Loading branch information
riasvdv authored Oct 6, 2020
1 parent 80d532a commit a664365
Show file tree
Hide file tree
Showing 2 changed files with 82 additions and 0 deletions.
14 changes: 14 additions & 0 deletions src/Search/Searchables.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

namespace Statamic\Search;

use Closure;
use Illuminate\Support\Arr;
use Illuminate\Support\Collection;
use Statamic\Facades\Asset;
Expand Down Expand Up @@ -65,11 +66,24 @@ public function contains($searchable)
public function fields($searchable): array
{
$fields = $this->index->config()['fields'];
$transformers = $this->index->config()['transformers'] ?? [];

return collect($fields)->mapWithKeys(function ($field) use ($searchable) {
$value = method_exists($searchable, $field) ? $searchable->{$field}() : $searchable->get($field);

return [$field => $value];
})->flatMap(function ($value, $field) use ($transformers) {
if (! isset($transformers[$field]) || ! $transformers[$field] instanceof Closure) {
return [$field => $value];
}

$transformedValue = $transformers[$field]($value);

if (is_array($transformedValue)) {
return $transformedValue;
}

return [$field => $transformedValue];
})->all();
}
}
68 changes: 68 additions & 0 deletions tests/Search/SearchablesTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
<?php

namespace Tests\Search;

use Statamic\Facades\Entry;
use Statamic\Search\Searchables;
use Tests\TestCase;

class SearchablesTest extends TestCase
{
/** @test */
public function it_transforms_values_set_in_the_config_file()
{
config()->set('statamic.search.indexes.default', [
'fields' => [
'title',
],
'transformers' => [
'title' => function ($value) {
return strtoupper($value);
},
],
]);

$index = app(\Statamic\Search\Comb\Index::class, [
'name' => 'default',
'config' => config('statamic.search.indexes.default'),
]);

$searchable = Entry::make()->data(['title' => 'Hello']);
$searchables = new Searchables($index);

$this->assertEquals([
'title' => 'HELLO',
], $searchables->fields($searchable));
}

/** @test */
public function if_a_transformer_returns_an_array_it_gets_combined_into_the_results()
{
config()->set('statamic.search.indexes.default', [
'fields' => [
'title',
],
'transformers' => [
'title' => function ($value) {
return [
'title' => $value,
'title_upper' => strtoupper($value),
];
},
],
]);

$index = app(\Statamic\Search\Comb\Index::class, [
'name' => 'default',
'config' => config('statamic.search.indexes.default'),
]);

$searchable = Entry::make()->data(['title' => 'Hello']);
$searchables = new Searchables($index);

$this->assertEquals([
'title' => 'Hello',
'title_upper' => 'HELLO',
], $searchables->fields($searchable));
}
}

0 comments on commit a664365

Please sign in to comment.