1<?php
2
3namespace Elastica\Multi;
4
5use Elastica\Response;
6use Elastica\ResultSet as BaseResultSet;
7use Elastica\Search as BaseSearch;
8
9class MultiBuilder implements MultiBuilderInterface
10{
11    /**
12     * @param BaseSearch[] $searches
13     */
14    public function buildMultiResultSet(Response $response, array $searches): ResultSet
15    {
16        $resultSets = $this->buildResultSets($response, $searches);
17
18        return new ResultSet($response, $resultSets);
19    }
20
21    private function buildResultSet(Response $childResponse, BaseSearch $search): BaseResultSet
22    {
23        return $search->getResultSetBuilder()->buildResultSet($childResponse, $search->getQuery());
24    }
25
26    /**
27     * @param BaseSearch[] $searches
28     *
29     * @return BaseResultSet[]
30     */
31    private function buildResultSets(Response $response, array $searches): array
32    {
33        $data = $response->getData();
34        if (!isset($data['responses']) || !\is_array($data['responses'])) {
35            return [];
36        }
37
38        $resultSets = [];
39        \reset($searches);
40
41        foreach ($data['responses'] as $responseData) {
42            $search = \current($searches);
43            $key = \key($searches);
44            \next($searches);
45
46            $resultSets[$key] = $this->buildResultSet(new Response($responseData), $search);
47        }
48
49        return $resultSets;
50    }
51}
52