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