1<?php
2
3declare(strict_types = 1);
4
5namespace Elasticsearch\Endpoints;
6
7use Elasticsearch\Common\Exceptions\RuntimeException;
8use Elasticsearch\Serializers\SerializerInterface;
9
10/**
11 * Class Msearch
12 *
13 * @category Elasticsearch
14 * @package  Elasticsearch\Endpoints
15 * @author   Zachary Tong <zach@elastic.co>
16 * @license  http://www.apache.org/licenses/LICENSE-2.0 Apache2
17 * @link     http://elastic.co
18 */
19class Msearch extends AbstractEndpoint
20{
21    /**
22     * @param SerializerInterface $serializer
23     */
24    public function __construct(SerializerInterface $serializer)
25    {
26        $this->serializer = $serializer;
27    }
28
29    /**
30     * @param array|string $body
31     */
32    public function setBody($body): Msearch
33    {
34        if (isset($body) !== true) {
35            return $this;
36        }
37
38        if (is_array($body) === true) {
39            $bulkBody = "";
40            foreach ($body as $item) {
41                $bulkBody .= $this->serializer->serialize($item)."\n";
42            }
43            $body = $bulkBody;
44        }
45
46        $this->body = $body;
47
48        return $this;
49    }
50
51    public function getURI(): string
52    {
53        $index = $this->index ?? null;
54        $type = $this->type ?? null;
55
56        if (isset($index) && isset($type)) {
57            return "/$index/$type/_msearch";
58        }
59        if (isset($index)) {
60            return "/$index/_msearch";
61        }
62        return "/_msearch";
63    }
64
65    /**
66     * @return string[]
67     */
68    public function getParamWhitelist(): array
69    {
70        return [
71            'search_type',
72            'max_concurrent_searches',
73            'typed_keys',
74            'pre_filter_shard_size',
75            'max_concurrent_shard_requests',
76            'rest_total_hits_as_int',
77            'ccs_minimize_roundtrips'
78        ];
79    }
80
81    /**
82     * @return array|string
83     * @throws RuntimeException
84     */
85    public function getBody()
86    {
87        if (isset($this->body) !== true) {
88            throw new RuntimeException('Body is required for MSearch');
89        }
90
91        return $this->body;
92    }
93
94    public function getMethod(): string
95    {
96        return 'POST';
97    }
98}
99