1<?php
2
3namespace Elastica;
4
5/**
6 * Represents elasticsearch task.
7 *
8 * @see https://www.elastic.co/guide/en/elasticsearch/reference/current/tasks.html
9 */
10class Task extends Param
11{
12    const WAIT_FOR_COMPLETION = 'wait_for_completion';
13    const WAIT_FOR_COMPLETION_FALSE = 'false';
14    const WAIT_FOR_COMPLETION_TRUE = 'true';
15
16    /**
17     * Task id, e.g. in form of nodeNumber:taskId.
18     *
19     * @var string
20     */
21    protected $_id;
22
23    /**
24     * Contains all status infos.
25     *
26     * @var \Elastica\Response Response object
27     */
28    protected $_response;
29
30    /**
31     * Data.
32     *
33     * @var array Data
34     */
35    protected $_data;
36
37    /**
38     * Client object.
39     *
40     * @var \Elastica\Client Client object
41     */
42    protected $_client;
43
44    public function __construct(Client $client, string $id)
45    {
46        $this->_client = $client;
47        $this->_id = $id;
48    }
49
50    /**
51     * Returns task id.
52     *
53     * @return string
54     */
55    public function getId()
56    {
57        return $this->_id;
58    }
59
60    /**
61     * Returns task data.
62     *
63     * @return array Task data
64     */
65    public function getData(): array
66    {
67        if (\is_null($this->_data)) {
68            $this->refresh();
69        }
70
71        return $this->_data;
72    }
73
74    /**
75     * Returns response object.
76     *
77     * @return \Elastica\Response
78     */
79    public function getResponse(): Response
80    {
81        if (\is_null($this->_response)) {
82            $this->refresh();
83        }
84
85        return $this->_response;
86    }
87
88    /**
89     * Refresh task status.
90     *
91     * @param array $options Options for endpoint
92     */
93    public function refresh(array $options = [])
94    {
95        $endpoint = new \Elasticsearch\Endpoints\Tasks\Get();
96        $endpoint->setTaskId($this->_id);
97        $endpoint->setParams($options);
98
99        $this->_response = $this->_client->requestEndpoint($endpoint);
100        $this->_data = $this->getResponse()->getData();
101    }
102
103    /**
104     * @return bool
105     */
106    public function isCompleted(): bool
107    {
108        $data = $this->getData();
109
110        return true === $data['completed'];
111    }
112
113    public function cancel(): Response
114    {
115        if (empty($this->_id)) {
116            throw new \Exception('No task id given');
117        }
118
119        $endpoint = new \Elasticsearch\Endpoints\Tasks\Cancel();
120        $endpoint->setTaskId($this->_id);
121
122        return $this->_client->requestEndpoint($endpoint);
123    }
124}
125