distantnative / search-for-kirby

Kirby 3 plugin for adding a search index (sqlite or Algolia).
43 stars 3 forks source link

Missing `$result` with `$site->search()` and Algolia #27

Closed marcus-at-localhost closed 3 years ago

marcus-at-localhost commented 3 years ago

Describe the bug

Using $site->search('ptfe') in the frontend, results in this:

image

This is the result array, before it throws the error

image

Building the index works, the search in the backend works and the data in Algolia backend is searchable as well.

I've got an Algolia Free Account for testing right now.

I think, what happens, if I look at the request from the search panel in the backend in Provider.php filterByCollection() the $collection is null.

But I don't understand how it get there for the $site->search('ptfe') call.

Edit: Ok, when I use search('ptfe') then $collection is null and it works as expected.

distantnative commented 3 years ago

$collection cannot be null - otherwise the if-statement above would catch it and the error would be different.

It seems like $result has no index id. I think Algolia renames it to objectID in its response.

If you would change site/plugins/search/src/models/Provider.php on line 117 from

return $collection->has($result['id']);

to

return $collection->has($result['id'] ?? $result['objectID'] ?? null);

Does this solve your problem?

marcus-at-localhost commented 3 years ago

It ends here. image

Unfortunately, I can't wrap my mind around it.

As I mentioned search('ptfe') works as expected.

marcus-at-localhost commented 3 years ago

I just noticed that I get the same error above in the panels when I use a Page field and want to search for an entry:

image

    protected function filterByCollection(array $results, $collection = null): array
    {
        // If no collection exists, return all results
        if ($collection === null) {
            return $results;
        }

        clock($results);

        // Otherwise remove the results that are not
        // part of the collection
        return array_filter($results, function ($result) use ($collection) {
            return $collection->has($result['id'] ?? $result['objectID'] ?? null);
        });
    }

image

The yellow marked object in the screenshot is the output of clock($results);

distantnative commented 3 years ago

Ok, I think I spotted my mistake.

Does it work when you replace this line: https://github.com/distantnative/search-for-kirby/blob/main/src/models/Providers/Algolia.php#L114

with:

        $results['hits'] = $this->filterByCollection($results['hits'], $collection);

?

distantnative commented 3 years ago

This should be solved with the 1.1.0-rc.1. Please let me know if not.