1<?php
2
3declare(strict_types = 1);
4
5namespace Elasticsearch\Endpoints;
6
7use Elasticsearch\Common\Exceptions\InvalidArgumentException;
8use Elasticsearch\Serializers\SerializerInterface;
9use Traversable;
10
11/**
12 * Class Bulk
13 *
14 * @category Elasticsearch
15 * @package  Elasticsearch\Endpoints
16 * @author   Zachary Tong <zach@elastic.co>
17 * @license  http://www.apache.org/licenses/LICENSE-2.0 Apache2
18 * @link     http://elastic.co
19 */
20class Bulk extends AbstractEndpoint implements BulkEndpointInterface
21{
22    /**
23     * @param SerializerInterface $serializer
24     */
25    public function __construct(SerializerInterface $serializer)
26    {
27        $this->serializer = $serializer;
28    }
29
30    /**
31     * @param string|array|Traversable $body
32     */
33    public function setBody($body): BulkEndpointInterface
34    {
35        if (empty($body)) {
36            return $this;
37        }
38
39        if (is_array($body) === true || $body instanceof Traversable) {
40            foreach ($body as $item) {
41                $this->body .= $this->serializer->serialize($item) . "\n";
42            }
43        } elseif (is_string($body)) {
44            $this->body = $body;
45            if (substr($body, -1) != "\n") {
46                $this->body .= "\n";
47            }
48        } else {
49            throw new InvalidArgumentException("Bulk body must be an array, traversable object or string");
50        }
51
52        return $this;
53    }
54
55    public function getURI(): string
56    {
57        $index = $this->index ?? null;
58        $type = $this->type ?? null;
59        if (isset($index) && isset($type)) {
60            return "/$index/$type/_bulk";
61        }
62        if (isset($index)) {
63            return "/$index/_bulk";
64        }
65        return "/_bulk";
66    }
67
68    public function getParamWhitelist(): array
69    {
70        return [
71            'wait_for_active_shards',
72            'refresh',
73            'routing',
74            'timeout',
75            'type',
76            '_source',
77            '_source_includes',
78            '_source_excludes',
79            'pipeline'
80        ];
81    }
82
83    public function getMethod(): string
84    {
85        return 'POST';
86    }
87}
88