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 MsearchTemplate
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 MsearchTemplate 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): MsearchTemplate
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/template";
58        }
59        if (isset($index)) {
60            return "/$index/_msearch/template";
61        }
62        return "/_msearch/template";
63    }
64
65    public function getParamWhitelist(): array
66    {
67        return [
68            'search_type',
69            'typed_keys',
70            'max_concurrent_searches',
71            'rest_total_hits_as_int',
72            'ccs_minimize_roundtrips'
73        ];
74    }
75
76    /**
77     * @throws RuntimeException
78     */
79    public function getBody()
80    {
81        if (isset($this->body) !== true) {
82            throw new RuntimeException('Body is required for MSearch');
83        }
84
85        return $this->body;
86    }
87
88    public function getMethod(): string
89    {
90        return 'POST';
91    }
92}
93