ideas icon indicating copy to clipboard operation
ideas copied to clipboard

Search Transformer classes for custom search fields

Open GertTimmerman opened this issue 3 years ago • 0 comments
trafficstars

We have a multi-site which we want connect with algolia. For that we want some custom fields based on the current entry. In the transformer attribute in the config file (search.php), you are not able to access the entry, only the field. Also, the config file will be clutered when you have a couple of indexes with transformers.

So my idea is to have the option to use a search transform class to return the fields you want.

You can create a TransformerContract.php in ./src/Search:

<?php

namespace Statamic\Search;

interface TransformerContract
{
    public function transform($searchable);
}

Then you have to add these lines in the Searchables.php file in ./src/Search:

use Statamic\Search\TransformerContract;

// below line 160
if (!is_array($transformers) && is_subclass_of($transformers, TransformerContract::class)) {
    $transformer = new $transformers();
    return $transformer->transform($searchable);
}

When you have for example a blog, the you can configure the index for the blog as this:

use App\Transformers\BlogTransformer;

'blog' => [
    'driver' => 'algolia',
    'searchables' => ['collection:articles'],
    'transformers' => BlogTransformer::class
],

And this is an example of the BlogTransformer class:

<?php

namespace App\Transformers;

use Statamic\Search\TransformerContract;

class BlogTransformer implements TransformerContract
{
    public function transform($searchable)
    {
        return [
            'title' => $searchable->title,
            'date' => $searchable->date()->format('Y-m-d'),
            'categories' => $searchable->categories ? $searchable->categories : $searchable->origin()->categories,
            'featured_description' => $searchable->featured_description,
            'published' => $searchable->published(),
            'locale' => $searchable->locale(),
            'url' => $searchable->url()
        ];
    }
}

GertTimmerman avatar May 16 '22 14:05 GertTimmerman