[PHP] A Meilisearch adapter for Pagerfanta

Published on 2023-05-21 • Modified on 2023-05-21

This snippet shows how to create a Meilisearch adapter for the Pagerfanta PHP library. As you can see, it is quite straightforward. I'll try to make a PR when I can find some time, don't hesitate to do it if you don't want to have this code in your application. You can use it like this:
$pagination = (new Pagerfanta(new MeilisearchAdapter($searchResult)))->setCurrentPage($page);
where $searchResult is a Meilisearch\Search\SearchResult object.


<?php

declare(strict_types=1);

namespace App\Search\Pager;

use Meilisearch\Search\SearchResult;
use Pagerfanta\Adapter\AdapterInterface;

/**
 * Adapter which calculates pagination from a Meilisearch SearchResult object.
 *
 * @template T
 *
 * @implements AdapterInterface<T>
 */
final readonly class MeilisearchAdapter implements AdapterInterface
{
    public function __construct(
        public SearchResult $searchResult
    ) {
    }

    /**
     * @phpstan-return int<0, max>
     */
    public function getNbResults(): int
    {
        return max(0, $this->searchResult->getTotalHits());
    }

    /**
     * @phpstan-param int<0, max> $offset
     * @phpstan-param int<0, max> $length
     *
     * @return array<int, T>
     */
    public function getSlice(int $offset, int $length): iterable
    {
        return $this->searchResult->getHits(); /** @phpstan-ignore-line */
    }
}

  Read the doc  Random snippet

  Work with me!