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 Response     $response
13     * @param BaseSearch[] $searches
14     *
15     * @return ResultSet
16     */
17    public function buildMultiResultSet(Response $response, array $searches): ResultSet
18    {
19        $resultSets = $this->buildResultSets($response, $searches);
20
21        return new ResultSet($response, $resultSets);
22    }
23
24    /**
25     * @param Response   $childResponse
26     * @param BaseSearch $search
27     *
28     * @return BaseResultSet
29     */
30    private function buildResultSet(Response $childResponse, BaseSearch $search): BaseResultSet
31    {
32        return $search->getResultSetBuilder()->buildResultSet($childResponse, $search->getQuery());
33    }
34
35    /**
36     * @param Response     $response
37     * @param BaseSearch[] $searches
38     *
39     * @return BaseResultSet[]
40     */
41    private function buildResultSets(Response $response, $searches): array
42    {
43        $data = $response->getData();
44        if (!isset($data['responses']) || !\is_array($data['responses'])) {
45            return [];
46        }
47
48        $resultSets = [];
49        \reset($searches);
50
51        foreach ($data['responses'] as $responseData) {
52            $search = \current($searches);
53            $key = \key($searches);
54            \next($searches);
55
56            $resultSets[$key] = $this->buildResultSet(new Response($responseData), $search);
57        }
58
59        return $resultSets;
60    }
61}
62