Task.php 2.4 KB

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